1

我有一个程序,其中 3 个线程试图按从 1 到 10 的顺序打印数字。我正在使用 aCountDownLatch来保持计数。

但是程序在打印 1 之后就停止了。

注意:我知道使用AtomicInteger而不是Integer可以工作。但我希望在当前代码中找出问题所在。

public class Worker implements Runnable {
    private int id;
    private volatile Integer count;
    private CountDownLatch latch;

    public Worker(int id, Integer count, CountDownLatch latch) {
        this.id = id;
        this.count = count;
        this.latch = latch;
    }

    @Override
    public void run() {
        while (count <= 10) {
            synchronized (latch) {
                if (count % 3 == id) {
                    System.out.println("Thread: " + id + ":" + count);
                    count++;
                    latch.countDown();
                }
            }
        }
    }

}

主程序:

public class ThreadSequence {
    private static CountDownLatch latch = new CountDownLatch(10);
    private volatile static Integer count = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Worker(0, count, latch));
        Thread t2 = new Thread(new Worker(1, count, latch));
        Thread t3 = new Thread(new Worker(2, count, latch));

        t1.start();
        t2.start();
        t3.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

编辑程序AtomicInteger

public class ThreadSequence {
    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new WorkerThread(0, atomicInteger));
        Thread t2 = new Thread(new WorkerThread(1, atomicInteger));
        Thread t3 = new Thread(new WorkerThread(2, atomicInteger));
        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println("Done with main");
    }
}


public class WorkerThread implements Runnable {
    private int id;
    private AtomicInteger atomicInteger;

    public WorkerThread(int id, AtomicInteger atomicInteger) {
        this.id = id;
        this.atomicInteger = atomicInteger;
    }

    @Override
    public void run() {
        while (atomicInteger.get() < 10) {
            synchronized (atomicInteger) {
                if (atomicInteger.get() % 3 == id) {
                    System.out.println("Thread:" + id + " = " + atomicInteger);
                    atomicInteger.incrementAndGet();
                }
            }

        }
    }
}
4

4 回答 4

4

但是程序在打印 1 之后就停止了。

不,这不是发生的事情。没有一个线程终止。

每个工人都有自己的count领域。其他线程不写入该字段。

因此,只有一个线程,其中if (count % 3 == id) {yield true,也就是带有 的线程id = 0。这也是唯一一个修改该count字段并修改它导致(count % 3 == id)false后续循环迭代中产生的线程,从而导致所有 3 个线程中的无限循环。

更改countstatic解决此问题。

编辑

对比Integer AtomicInteger是可变的。它是一个包含int可以修改的值的类。使用Integer该字段的每一次修改都会替换它的值,但是使用AtomicInteger你只修改AtomicInteger对象内部的值,但是所有 3 个线程继续使用同一个AtomicInteger实例。

于 2016-08-07T11:46:21.697 回答
1

您的“计数”是每个线程的不同变量,因此在一个线程中更改它不会影响其余线程,因此他们都在等待它更改,没有任何人可以做到这一点。

于 2016-08-07T11:45:46.573 回答
1

在 Worker 类中保留countas 静态成员 - 对类中的所有对象通用。

于 2016-08-07T11:49:26.040 回答
0

您可以使用以下代码使用多个线程打印序列号 -

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadCall extends Thread {

    private BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    private ThreadCall next;

    public void setNext(ThreadCall t) {
        this.next = t;
    }

    public void addElBQ(int a) {
        this.bq.add(a);
    }

    public ThreadCall(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        int x = 0;
        while(true) {
            try {
                x = 0;
                x = bq.take();
                if (x!=0) {
                    System.out.println(Thread.currentThread().getName() + " =>" + x);
                    if (x >= 100) System.exit(0); // Need to stop all running threads
                    next.addElBQ(x+1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_COUNT = 10;
        List<ThreadCall> listThread = new ArrayList<>();

        for (int i=1; i<=THREAD_COUNT; i++) {
            listThread.add(new ThreadCall("Thread " + i));
        }

        for (int i = 0; i < listThread.size(); i++) {
            if (i == listThread.size()-1) {
                listThread.get(i).setNext(listThread.get(0));
            }
            else listThread.get(i).setNext(listThread.get(i+1));
        }

        listThread.get(0).addElBQ(1);

        for (int i = 0; i < listThread.size(); i++) {
            listThread.get(i).start();
        }
    }
}

我希望这能解决你的问题

于 2017-04-03T11:05:54.660 回答