public class TestThread {
public static void main(String[] args){
System.out.println("线程执行之前!");
Thread thread1=new Thread(new MyRunnable(),"线程1");
thread1.start();
synchronized(thread1){
try {
System.out.println("线程1进入wait()");
thread1.wait();//立即释放对象锁,让另一个同步块执行
System.out.println("线程1已经进入wait()");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程执行之后!");
}}class MyRunnable implements Runnable{
public void run(){
synchronized(this){
for(int i=0;i<5;i++){

if(count>0){
System.out.println(Thread.currentThread().getName()+"count的值为:"+count--);
try{
System.out.println("线程进入notify()之前");
this.notify();
System.out.println("线程进入notify()之后");
}catch(Exception e){
e.printStackTrace();
}
}

}
}
}
private static int count=5;
}代码执行后结果如下:线程执行之前!
线程1进入wait()
线程1count的值为:5
线程进入notify()之前
线程进入notify()之后
线程1count的值为:4
线程进入notify()之前
线程进入notify()之后
线程1count的值为:3
线程进入notify()之前
线程进入notify()之后
线程1count的值为:2
线程进入notify()之前
线程进入notify()之后
线程1count的值为:1
线程进入notify()之前
线程进入notify()之后
线程1已经进入wait()
线程执行之后!请问调用了notify()之后不是就已经唤醒了最初的那个同步块吗,然而 "线程1已经进入wait()" 这句在最后才执行,各位求教啊
多线程javathread

解决方案 »

  1.   

    Obj.wait(),与Obj.notify()必须要与synchronized(Obj)一起使用,也就是wait,与notify是针对已经获取了Obj锁进行操作,从语法角度来说就是Obj.wait(),Obj.notify必须在synchronized(Obj){...}语句块内。从功能上来说wait就是说线程在获取对象锁后,主动释放对象锁,同时本线程休眠。直到有其它线程调用对象的notify()唤醒该线程,才能继续获取对象锁,并继续执行。相应的notify()就是对对象锁的唤醒操作。但有一点需要注意的是notify()调用后,并不是马上就释放对象锁的,而是在相应的synchronized(){}语句块执行结束,自动释放锁后,JVM会在wait()对象锁的线程中随机选取一线程,赋予其对象锁,唤醒线程,继续执行。这样就提供了在线程间同步、唤醒的操作。Thread.sleep()与Object.wait()二者都可以暂停当前线程,释放CPU控制权,主要的区别在于Object.wait()在释放CPU同时,释放了对象锁的控制。
      

  2.   

    这两行换个位置试试。
    for(int i=0;i<5;i++){
    synchronized(lock){
      

  3.   

    所以这个   System.out.println("线程1已经进入wait()");  最后咯
      

  4.   

    错误有3
    1、不是用一把锁 thread1 不是 MyRunnable  自然和this不是一把锁
    2、锁在循环外  循环执行完了 主线程才有执行权
    3、cpu给线程的也是时间片  在时间片内thread1已经结束了看不出效果  需要给出 Thread.yield();
    修正后代码public class TestThread {
    public static void main(String[] args){
    System.out.println("线程执行之前!");
    MyRunnable my = new MyRunnable();
    Thread thread1=new Thread(my,"线程1");
    thread1.start();
    synchronized(my){ //my与this才是一把锁
    try {
    System.out.println("线程1进入wait()");
    my.wait();//立即释放对象锁,让另一个同步块执行
    System.out.println("线程1已经进入wait()");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("线程执行之后!");

    }}class MyRunnable implements Runnable{
    public void run(){
    for(int i=0;i<5;i++) //循环在锁外面
    {
    synchronized(this) //同理锁在循环里面
    {
    if(count>0){
    System.out.println(Thread.currentThread().getName()+"count的值为:"+count--);
    try{
    System.out.println("线程进入notify()之前");
    this.notify();
    System.out.println("线程进入notify()之后");
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    Thread.yield(); //防止cpu不给主线程执行权
    }
    }
    }
    private static int count=5;
    }