【发布时间】:2020-09-09 21:29:54
【问题描述】:
我有两个文件,App.java 和 Runner.java
App.java -->
public class App {
private static Thread thread1 = new Runner(1);
private static Thread thread2 = new Runner(2);
public static void main(String[] args) throws InterruptedException {
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.printf("Count = %d\n", Runner.getCount());
}
}
Runner.java -->
public class Runner extends Thread {
private volatile static int count = 0;
private int option = 0;
private synchronized void increment() {
count++;
}
private synchronized void decrement() {
count--;
}
public Runner(int option) {
this.option = option;
}
public static int getCount() {
return count;
}
@Override
public void run() {
switch (option) {
case 1:
for (int i = 1; i <= 10000; i++) {
increment();
}
break;
case 2:
for (int i = 1; i <= 10000; i++) {
decrement();
}
break;
}
}
}
在这里,我试图从mainthread 创建两个threads,并从两个线程访问一个公共variable,其中threads 将同时操纵这个公共variable。
我正在尝试为 synchronized 关键字的实现创建一个演示。
在我的例子中,Runner.java -
我正在使用 extends keyword 和 overriding run() method 在正文中制作 Runner class child 类 Thread。
接下来,我使用constructor 获取option 并在switch - case block 中运行run() 方法中的相应代码。公共变量为count,即static,初始值为0。
有两个methods,都使用synchronizedkeyword-increment()和decrement(),分别将count的值加1和减1。
对于option 1 run() 方法使用for loop 运行increment() 10,000 次。
对于option 2 run() 方法使用for loop 运行decrement() 10,000 次。
因此count的最终值应该是0。
在App.java -
我正在创建两个threads - thread1、thread2,它们是Runner class 的实例,并分别传递constructor argument 1 和2。
我正在使用thread.start() 运行两个threads 并使用thread.join() 等待两个threads 完成
现在,我正在打印count 的值。该值预计为 0。但事实并非如此。在每次执行中,它都接近于 0,但不是 0。
那么,我哪里出错了以及如何更正我的代码?
【问题讨论】:
标签: java multithreading synchronized