62,628
社区成员
发帖
与我相关
我的任务
分享
public class Test{
public static void main(String[] args){
Object o = new Object();
Task1 task1 = new Task1(o);
Task2 task2 = new Task2(o);
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
thread1.start();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
thread2.start();
}
}
class Task1 implements Runnable{
public Task1(Object o){
this.o = o;
}
@Override
public void run(){
synchronized(o){
try{
System.out.printf("%s:(1)这个线程先启动.但是到达wait()的时候本线程会停止并交出对象的占有权\n",Thread.currentThread().getName());
o.wait();//将控制权交给其他对o对象进行同步的线程.
System.out.printf("%s:(5)当其他的线程调用对象的notify/notifyAll方法的时候会结束本线程的等待状态.\n",Thread.currentThread().getName());
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
private Object o;
}
class Task2 implements Runnable{
public Task2(Object o){
this.o = o;
}
@Override
public void run(){
synchronized(o){
try{
System.out.printf("%s:(2)线程启动,并且等待1秒钟后调用对象的notifyAll().\n",Thread.currentThread().getName());
Thread.sleep(1000);
o.notifyAll();
System.out.printf("%s:(3)这里已经调用了对象的notifyAll()方法,但是由于仍然处于同步代码块中,所以需要继续执行本线程.\n",Thread.currentThread().getName());
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.printf("%s:(4)这里会继续先执行,执行完后再执行其他对应对象的同步线程.\n",Thread.currentThread().getName());
}//锁自动释放
}
private Object o;
}