1

我无法弄清楚以下代码中的问题:
我有一个可以暂停和恢复的线程
代码如下:

public class CustomThread implements Runnable {   

    private volatile boolean stop;  
    private volatile boolean suspend;  

    String[] names = new String[]{  
            "A", "B","C","D","E", "F", "G","H","I","J","K", "L"  
    };  

    public CustomThread(){  
        Collections.shuffle(Arrays.asList(names));  
        System.out.println("Available names:");  
        System.out.println(Arrays.asList(names));  

    }  

    @Override  
    public void run() {  

        while(!stop){             
            synchronized (this) {  
                if(suspend){  
                    try {  
                        System.out.println("Got suspended");  
                        wait();  
                        System.out.println("Resumed");  
                    } catch (InterruptedException e) {  
                        System.out.println("Got interupted");  
                    }  
                }     
                else System.out.println("Suspend false");  
            }  
            int randomIdx = new Random().nextInt(names.length);  
            System.out.println(names[randomIdx]);             
        }  
    }  

    public synchronized void suspend(){  
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>Suspend true");  
        suspend = true;  
    }  

    public synchronized void resume(){  
        suspend = false;  
        notify();  
    }    
}  

我运行以下简单代码:

public class CustomTest {  

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {  
        CustomThread c = new CustomThread();  
        Thread t = new Thread(c);  
        t.start();  
        Thread.sleep(5000);  
        System.out.println("++++++++++++++++++++++++++++++++");         
        c.suspend();  
    }  
}

我期望看到的是:
线程自定义运行,主线程休眠,主线程暂停自定义线程,c.suspend()并且由于main终止并且没有人恢复线程,线程保持在wait状态。
但我看到的是CustomThread连续打印Suspend false和来自names.

这里有什么问题?就像Thread.sleep(5000)and c.suspend()in main 什么都不做。

4

2 回答 2

1

代码写得很好,但是您的问题可能是您正在通过 Eclipse 运行它并且您压倒了控制台。缩短延迟时间main,您会看到好的结果。

注意:您的suspend方法不需要,synchronized因为它只写入volatile变量。

于 2012-07-20T11:23:05.993 回答
0

而不是if(suspend)你应该有while(suspend),在这里查看javadoc中的解释:http: //docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28%29

来自的javadoc Object.wait()

...可能会出现中断和虚假唤醒,并且应该始终在循环中使用此方法

于 2012-07-20T10:52:30.390 回答