【发布时间】:2018-10-16 13:07:51
【问题描述】:
我是线程新手。我想让两个线程将整数增加到某个值。因为 int 类型是不可变的,所以我切换到原子整数。我还尝试将一个 int 包装到一个类中,但这也不起作用。我也尝试了 static/volatile int ,但没有奏效。我也尝试使用公平政策。主要问题是“counterObj”没有正确递增,即使它被注入到两个线程,它仍然设置为 0。
我预期的跑步行为:
thread value
thread 0 0
thread 1 1
thread 0 2
...
到目前为止我写的:
import java.util.concurrent.atomic.AtomicInteger;
public class Application {
public static void main(String[] args) {
Application app = new Application();
try {
app.launch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void launch() throws InterruptedException {
int increments = 100;
AtomicInteger counterObj = new AtomicInteger(0);
CounterThread th1 = new CounterThread("1", counterObj, increments);
CounterThread th2 = new CounterThread("2", counterObj, increments);
th1.start();
th2.start();
System.out.println(counterObj.get());
}
}
和
import java.util.concurrent.atomic.AtomicInteger;
public class CounterThread implements Runnable {
private final String threadID;
private AtomicInteger counterObj;
private int bound;
public CounterThread(String threadID, AtomicInteger counter, int bound) {
this.threadID = threadID;
this.counterObj = counter;
this.bound = bound;
}
@Override
public synchronized void run() {
while (counterObj.get() < bound) {
synchronized (this) {
counterObj.incrementAndGet();
}
}
System.out.println("Thread " + threadID + " finished");
}
public void start() throws InterruptedException {
Thread thread = new Thread(this, threadID);
thread.join();
thread.start();
}
}
干杯!
【问题讨论】:
-
仅作记录:调用您的类 counterThread 然后使其 实现 可运行,但在内部创建一个 Thread 对象本身......这是一个非常奇怪的设计。它给你的代码增加了大量的混乱,没有任何必要这样做。使类扩展线程本身,或者给它一个不同的名称,以更好地描述它正在做什么。
-
还有start方法...我觉得线程的控制应该在main(调用join()和start)...
-
-
不要同步运行,也不要在同步方法中执行 synchronize(this)。您需要在共享对象上进行同步才能使用。
-
AtomicInteger的全部意义在于它本身强制执行原子性。您不需要需要围绕AtomicInteger.incrementAndGet()进行自己的同步,因为该类保证它自己会以原子方式进行。
标签: java java-threads