21 线程同步
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了21 线程同步相关的知识,希望对你有一定的参考价值。
关键字:synchronized
class Service
{
public void fun1()
{
synchronized(this)//同步代码块
{
try{
Thread.sleep(3*1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("fun1");
}
}
public void fun2()
{
synchronized(this) //同步代码块
{
System.out.println("fun2");
}
}
}
class MyThread1 implements Runnable
{
private Service service;
public MyThread1(Service service)
{
this.service=service;
}
public void run()
{
Serive.fun1();
}
}
class MyThread2 implements Runnable
{
private Service service;
public MyThread2(Service service)
{
this.service=service;
}
public void run()
{
Serive.fun2();
}
}
class Test
{
public static void main(String args[])
{
Service service=new Service();
Thread t1=new Thread(new MyThread1(service));
Thread t2=new Thread(new MyThread2(service));
t1.start();
t2.start();
}
}
以上是关于21 线程同步的主要内容,如果未能解决你的问题,请参考以下文章