站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题关于线程中wait(),notify()的一个问题?

关于线程中wait(),notify()的一个问题?

摘要: 关于线程中wait(),notify()的一个问题?


源代码:
package javasave.secondecode.packagecode;

public class ThreadCode implements Runnable{
static int value=0;
static ThreadCode test=new ThreadCode();
static Thread runA=new Thread(test,"runA");
static Thread runB=new Thread(test,"runB");
public void run(){
if (Thread.currentThread().getName().equalsIgnoreCase("runA")) {
synchronized(this) {
try{
wait();
} catch(InterruptedException e){
System.out.println("run error");
}
}
}

while(value!=100){
value++;
System.out.println(Thread.currentThread().getName()+"/n"+value);
if((value%10)==0){

synchronized(this) {
try{
wait();
notify();
} catch(InterruptedException e){
System.out.println("run error");
}
}
}
}
}
public static void main(String args[]){
runA.start();
runB.start();
}
}
为什么运行结果是
runB
1
runB
2
runB
3
runB
4
runB
5
runB
6
runB
7
runB
8
runB
9
runB
10


一碰到runA线程就wait了,当然只有B的结果了


哈哈,楼上正解


楼主大概想问为什么runA在synchronized块中等待时,runB执行吧
wait()方法是让当前的线程等待,它有一个很重要的特点是它会释放
它的锁,即解锁(具体就是你这里的this对象),所以runB讲获得执行
的机会

顺便说下sleep()方法,如果你在同步块中用的是sleep()而不是
wait()结果会不同,原因很简单,sleep()方法并没有释放它的锁
即使它休眠别的线程也不会获得执行次同步块的权利,除非
sleep()结束,解锁




当然你不能讲那个同步块放在if中
因为这样根本没什么意义,里面根本
不需要同步(因为只有runA才能进去的)


↑返回目录
前一篇: 新手请教,困惑。(关于java机制的)
后一篇: 拷贝枚举器以加强效率