无法暂停我的帖子!为什么?

时间:2012-07-20 10:37:54

标签: java multithreading concurrency

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

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)c.suspend()没有做任何事情一样。

2 个答案:

答案 0 :(得分:1)

编写的代码很好,但是您的问题可能是您通过Eclipse运行它并且您正在压倒控制台。在main放一个较短的延迟,你会看到好的结果。

注意:您的suspend方法不一定是synchronized,因为它只会写入volatile变量。

答案 1 :(得分:0)

您应该if(suspend)而不是while(suspend),请在此处查看javadoc中的说明:http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28%29

来自Object.wait()的javadoc:

  

...中断和虚假的唤醒   可能,这个方法应该总是在循环中使用