Java线程无响应notifyAll()

时间:2012-11-21 21:54:44

标签: java multithreading wait

我正在开发一个演示程序,它显示了处理线程的不同方式的影响。我正在使用一个简单的任务,即获取一个char数组并构建一个名称,将每个char发送到一个StringBuilder,该StringBuilder调用一个名为NameBuilder的runnable,后者又使用带有synchronized方法的letterAdder类和一个静态StringBuilder变量来保存名称,因为它是建成。这个结构松散地基于Bruce Eckel在“Thinking in Java”中的WaxoMatic示例

以下是我用于notifyAll()方法的代码:

import java.util.List;
import java.util.concurrent.*;

class LetterAdder{
    public static StringBuilder currName = new StringBuilder();
    public static boolean busyAdding = false;

    public synchronized void addLetterSynchWithNotifyAll(char letter) throws InterruptedException{
        while (busyAdding){
            System.out.println("Letter " +letter+" has to wait");
            wait();
        }
        busyAdding=true;
        System.out.println("About to add " + letter + " - ");
        currName.append(letter);
        System.out.println("name is now " + currName);
        busyAdding=false;
    }

    public synchronized void doNotifyAll(char letter) throws InterruptedException{
        System.out.print(letter + " is notifying all");
        notifyAll();
    }
}

class NameBuilder implements Runnable{
    private LetterAdder adder = new LetterAdder();
    private char nextLetter;

    public NameBuilder(char nextLetter){
        adder = new LetterAdder();
        this.nextLetter=nextLetter;
    }

    public void run(){
        try{
            adder.addLetterSynchWithNotifyAll(nextLetter);
                adder.doNotifyAll(nextLetter);
        } catch (InterruptedException e) {
            System.out.println("Letter "+nextLetter+" interrupted!");
        }

        //tie up thread for specified time to ensure other threads go to wait 
        try{
            TimeUnit.SECONDS.sleep(1);
        } catch(Exception e){}
    }
}

public class NotifyDemo {
    public static void main(String[] args) {
        char[] chars = {'M', 'a','r','t','i','n'};
        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i=0; i<chars.length; i++){
            NameBuilder builder = new NameBuilder(chars[i]);
            pool.execute(builder);
        }

        System.out.println("\nWill shutdown thread pool in 20 seconds");
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {}
        System.out.println("\nAbout to shutdown thread pool ");
        List<Runnable> tasks = pool.shutdownNow();
        if (!tasks.isEmpty()){
            for (Runnable r: tasks){
                System.out.println("Uncompleted task: "+r.toString());
            }
        }
    }
}


/** Output
About to add M - 
Letter a has to wait
name is now M
Letter r has to wait
M is notifying allLetter t has to wait
About to add i - 

Will shutdown thread pool in 20 seconds
Letter n has to wait
name is now Mi
i is notifying all
About to shutdown thread pool 
Letter a interrupted!
Letter t interrupted!
Letter n interrupted!
Letter r interrupted!
*/

从输出中的打印语句中可以看出,字母在到达busyAdding监视器时被阻止并打印等待消息,但即使发送了notifAlly(),它们也永远不会退出等待状态。

另外,我希望中断的线程出现在shutdownNow()语句返回的List中,但列表为空。

我有一种感觉我错过了一些明显的东西,有人能发现我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

您正在分享不同加法器之间的busyAdding,但会锁定并通知每个不同的加法器。

这意味着可能发生以下情况。假设你创建了三个加法器,'O','p'和's',第一个可以输入 addLetterSynchWithNotifyAll ,通过后卫并将busy信号设置为true。现在,接下来的两名参赛者进入,并被卡在后卫。当第一个线程存在时,它通知在第一个跑步者处等待的所有线程(此时没有)。您想要在对象之间共享信号。

您可以将 addLetterSynchWithNotifyAll 设为静态,这意味着同步将在类级别上,然后您需要将等待更改为类,而不是实例。或者,您可以创建用于同步和等待的公共锁定对象。

如果您将方法设置为静态,请注意没有其他线程将进入该方法,因为它们现在已在同一对象上同步,并且您无需使用 busyAdding 进行保护。

相关问题