日期:2014-05-20  浏览次数:20712 次

请教一下,为什么我无法叫醒wait的线程?
Java code


public class ThreadTest3 {

    
    public static void main(String[] args) throws InterruptedException {
        
        new MyThread();
        MyThread mt = new MyThread();
        Thread t = new Thread(mt);        
        t.start();                        
        
        for(int i = 0;i < 20; i++){
            System.out.println("我是主线程。i:  " + i);
            Thread.sleep(1000);
            if(i == 10){new MyThread().call();}
        }
    }
    

}

class MyThread implements Runnable{
    Thread th1;

    public void run() {
        for(int i = 0;i < 10;i++){
            System.out.println("我是二线程。i:  " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(i == 5){
                wat();
            }
        }
        
    }    

    public synchronized void call()
        notifyAll();
    }
    
    public synchronized void wat(){
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    

}




------解决方案--------------------
Java code

public class ThreadTest3 {
    public static void main(String[] args) throws InterruptedException {
        
        new MyThread();
        MyThread mt = new MyThread();
        Thread t = new Thread(mt);        
        t.start();                        
        
        for(int i = 0;i < 20; i++){
            System.out.println("我是主线程。i:  " + i);
            Thread.sleep(1000);
            if(i == 10){
                mt.call();
            }
        }
    }
    

}

class MyThread implements Runnable{
    public void run() {
        for(int i = 0;i < 10;i++){
            System.out.println("我是二线程。i:  " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(i == 5){
                this.wat();
            }
        }
    }    

    public synchronized void call(){
        this.notifyAll();
    }
    
    public synchronized void wat(){
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }