我需要这个可以访问相同数据的线程同时执行而不会相互混淆,所以Thread.join()我一直在尝试使用同步方法。问题是我根本看不到任何变化,它一直给我带来与使用它们之前相同的结果。我什至不知道我到底做错了什么,同步方法假设阻止其他同步方法在完成之前执行,对吗?希望你能给我一些关于正在发生的事情的线索。
public class ThreadSync{
public static void main(String[] args) throws InterruptedException {
//if execute properly
//output can't be other than 0
while(true) {
ChangeValue counter = new ChangeValue();
Threads t = new Threads(counter,"up");
Threads t2 = new Threads(counter,"down");
Threads t3 = new Threads(counter,"print");
t.start();
t2.start();
t3.start();
}
}
}
class Threads extends Thread{
Threads(ChangeValue obj, String act){
counter = obj;
action = act;
}
@Override
public void run() {
switch(action) {
case ("up"): counter.up(); break;
case ("down"): counter.down(); …Run Code Online (Sandbox Code Playgroud)