如何解决在Java多线程中使用synced关键字时,没有得到预期的结果
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;
}
}
}
在这里,我尝试从threads
main
创建两个thread
,并从两个variable
都将对此进行操作的线程中访问一个公用threads
共同的variable
。
我正在尝试创建用于实现synchronized
关键字的演示。
在我的示例中,在Runner.java
-
我使用Runner
class
和child
将{{1}设为Thread
extends
类的keyword
}} overriding
。
接下来,我使用run()
获取method
,并在constructor
option
中以run()
方法运行相应的代码。公用变量是switch - case
,它是block
,初始值为0。
有两个count
,都使用static
methods
-synchronized
和keyword
,它们分别将count的值增加或减少1。 / p>
对于increment()
decrement()
,方法使用option 1
来运行run()
10,000次。
对于for loop
,increment()
方法使用option 2
来运行run()
10,000次。
因此for loop
的最终值应为0。
在decrement()
中-
我正在创建两个count
-App.java
,threads
,它们分别是thread1
的实例,并分别传递thread2
Runner class
1和2。
我正在使用constructor
运行两个argument
,并等待使用threads
完成两个thread.start()
现在,我正在打印threads
的值。该值应为0。但事实并非如此。在每次执行中,它接近0,但不接近0。
那么,我要去哪里出错了以及如何更正我的代码?
解决方法
busyness
是静态的,意味着只有一个这样的变量。
count
和increment
都不是静态的,这意味着它们在decrement
上是同步的-这是两个单独的this
实例。
将这些方法设为静态:
Runner
或使用显式互斥对象:
private synchronized static void increment() {
count++;
}
private synchronized static void decrement() {
count--;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。