0

这是某种Java Puzzler,我偶然发现并无法真正解释。也许有人可以?

以下程序在短时间内挂起。有时在 2 次输出之后,有时在 80 次之后,但几乎总是在正确终止之前。如果第一次没有发生,您可能需要运行几次。

public class Main {
    public static void main(String[] args) {
        final WorkerThread[] threads = new WorkerThread[]{ new WorkerThread("Ping!"), new WorkerThread("Pong!") };
        threads[0].start();
        threads[1].start();

        Runnable work = new Runnable() {
            private int counter = 0;
            public void run() {
                System.out.println(counter + " : " + Thread.currentThread().getName());
                threads[counter++ % 2].setWork(this);
                if (counter == 100) {
                    System.exit(1);
                }
            }
        };

        work.run();
    }
}

class WorkerThread extends Thread {
    private Runnable workToDo;

    public WorkerThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        while (true){
            if (workToDo != null) {
                workToDo.run();
                workToDo = null;
            }
        }
    }

    public void setWork(Runnable newWork) {
        this.workToDo = newWork;
    }
}

现在,很明显,繁忙的等待循环通常不是一个好主意。但这不是关于改进,而是关于了解正在发生的事情。

由于一切都按预期工作,WorkerThread.setWork()或者synchronized当该WorkerThread.workToDo字段设置为时,volatile我怀疑存在内存问题。

但究竟为什么会发生呢?调试无济于事,一旦您开始单步执行,一切都会按预期运行。

解释将不胜感激。

4

3 回答 3

2
  1. 第一个问题是您正在Runnable workToDomain线程设置,然后在没有同步的 2 个分叉线程中读取它。任何时候你在多个线程中修改一个字段,它都应该被标记为volatile或某人synchronized

    private volatile Runnable workToDo;
    
  2. 此外,由于多个线程都在这样做,counter++所以也需要synchronized. 我AtomicInteger为此推荐一个。

    private AtomicInteger counter = new AtomicInteger(0);
    ...
    threads[counter.incrementAndGet() % 2].setWork(this);
    
  3. 但我认为真正的问题可能是竞争条件之一。两个线程都可以将 设置为workToDoRunnable然后让它们都返回并将其设置回 ,null这样它们就会永远旋转。我不知道如何解决这个问题。

    1. threads[0] has it's `workToDo` set to the runnable.  It calls `run()`.
    2. at the same time threads[1] also calls `run()`.
    3. threads[0] sets the `workToDo` on itself and threads[1] to be the runnable.
    4. at the same time threads[1] does the same thing.
    5. threads[0] returns from the `run()` method and sets `workToDo` to be `null`.
    6. threads[1] returns from the `run()` method and sets `workToDo` to be `null`.
    7. They spin forever...
    

而且,正如您提到的,自旋循环很疯狂,但我认为这是一个演示线程程序。

于 2013-04-23T21:34:35.163 回答
1

问题发生在这几行之间:

workToDo.run();
workToDo = null;

假设发生以下事件序列:

- Original Runnable runs.  "Ping!".setWork() called
- Ping! thread realizes workToDo != null, calls run(), the stops between those two lines
  - "Pong!".setWork() called
- Pong! thread realizes workToDo != null, calls run()
  - "Ping!".setWork() called
- Ping! thread resumes, sets workToDo = null, ignorantly discarding the new value
- Both threads now have workToDo = null, and the counter is frozen at 2,...,80
  Program hangs
于 2013-04-23T21:44:55.227 回答
0

我的 2 美分....

import java.util.concurrent.atomic.AtomicReference;

class WorkerThread extends Thread {
    private AtomicReference<Runnable> work;

    public WorkerThread(String name) {
        super(name);
        work = new AtomicReference<Runnable>();
    }

    @Override
    public void run() {
        while (true){
            Runnable workToDo = work.getAndSet(null);
            if ( workToDo != null ) {
                workToDo.run();
            }
        }
    }

    public void setWork(Runnable newWork) {
        this.work.set(newWork);
    }
}
于 2014-08-14T16:41:40.057 回答