我尝试使用Synchronized方法,但我遇到了一些有趣的行为,例如:
我有三个线程 ThreadA - 调用递增方法, ThreadB 调用递减方法, ThreadC 打印当前值; 但有些值看起来不正确:
调试: 准备线程 假 的 1 0 0 0 0 0 的 1 0 0 0 0 0 0 0 0 0 0 0 ....
当它应该具有全0和1或其他值时;
我的代码如下:
package concurrency;
public class Synchronization {
public static void main(String[] args) throws InterruptedException {
System.out.println("Preparing threads");
Counter cnt = new Counter();
Thread threadA = new Thread(new ThreadA(cnt));
Thread threadB = new Thread(new ThreadB(cnt));
Thread ThreadC = new Thread (new ThreadC(cnt));
threadA.start();
threadB.start();
ThreadC.start();
}
private static class ThreadA implements Runnable {
private final Counter counter;
public ThreadA(Counter cnt) {
counter = cnt;
}
@Override
public void run() {
Thread.currentThread().setName("ThreadA");
System.out.println(((Boolean)
Thread.currentThread().isInterrupted()).toString());
try {
while (!Thread.currentThread().isInterrupted()) {
counter.Increment();
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException ThreadA");
}
System.out.println("ThreadA finished");
}
}
private static class ThreadB implements Runnable {
private final Counter counter;
public ThreadB(Counter cnt) {
counter = cnt;
}
@Override
public void run() {
Thread.currentThread().setName("ThreadB");
try {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
counter.Decrement();
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("InterruptedExcepion threadB");
}
System.out.println("ThreadB Finished");
}
}
private static class ThreadC implements Runnable {
private final Counter counter;
public ThreadC(Counter cnt) {
counter = cnt;
}
@Override
public void run() {
Thread.currentThread().setName("ThreadC");
try {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
System.out.println(counter.getValue());
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("InterruptedExcepion threadB");
}
System.out.println("ThreadB Finished");
}
}
private static class Counter {
private int value = 0;
public synchronized void Increment() {
value++;
}
public synchronized void Decrement() {
value--;
}
public synchronized int getValue() {
return value;
}
}
}
答案 0 :(得分:0)
我不知道你在这里看到的是意外的。此代码有3个线程使用公共共享计数器。有足够的同步来确保线程不会以无效方式修改共享数据或查看过时值。但输出将根据哪些线程获得更多CPU时间而变化。不要求这些线程以任何特定顺序运行,运行什么线程以及谁获得锁定可能看起来是任意的。这样的输出将是不可预测的。