线程同步问题,来的都给分
xuqq 2004-08-09 03:22:56 问问如下程序中,Synchronized(obj)如何锁的。
程序运行结果如下:
Thread-0 is waitting
Thread-1 is waitting
Thread-2 is will wake up some thread
Thread-0 will wake up
以此结果为例,请前辈讲述过程。
import java.lang.*;
public class notify {
public notify() {
}
public static void main(String[] args) {
Object obj=new Object();
Thread wait1=new Thread(new LockWait(obj));
Thread wait2=new Thread(new LockWait(obj));
Thread notify1=new Thread(new LockNotify(obj));
wait1.start();
wait2.start();
notify1.start();
}
}
class LockWait implements Runnable{
private Object obj;
public LockWait(Object obj){
this.obj=obj;
}
public void run(){
synchronized(obj){
try{
System.out.println(Thread.currentThread().getName()+" is waiting ");
obj.wait();
System.out.println(Thread.currentThread().getName() +" woke up ");
}
catch (InterruptedException e){
}
}
}
}
class LockNotify implements Runnable{
Object obj;
public LockNotify(Object obj){
this.obj=obj;
}
public void run(){
synchronized(obj){
System.out.println(Thread.currentThread().getName()+" will wake up some thread ");
obj.notify();
}
}
}