关键字: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();
}
}