我尝试使用同步方法,但我遇到了一些有趣的行为,例如:
我有三个线程ThreadA - 调用 Increment 方法,调用 Decrement 方法的ThreadB和打印当前值的ThreadC;但有些值看起来不正确:
调试:准备线程 false 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;
}
}
}
我不知道你在这里看到了什么出乎意料的。这段代码有 3 个使用公共共享计数器的线程。有足够的同步以确保线程不会以无效的方式修改共享数据或看到过时的值。但是输出将根据哪些线程何时获得更多 CPU 时间而有所不同。没有要求这些线程以任何特定的顺序运行,运行什么线程以及谁获得锁可能看起来是任意的。由此产生的输出将是不可预测的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句