任何人都可以告诉我为什么synchronized关键字不起作用。
package Threading;
class NewThreadt extends Thread {
synchronized void dota(int a){
System.out.println(a);
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
dota(i) ;
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
System.out.println(Thread.currentThread());
}
}
class abc {
public static void main(String args[]) {
NewThreadt t=new NewThreadt();
NewThreadt q=new NewThreadt();
t.start();
q.start();
System.out.println("Main thread exiting.");
}
}
输出我正在执行上述程序:
5
5
4
4
3
3
2
2
1
1
我想要的输出:
5
4
3
2
1
5
4
3
2
1
答案 0 :(得分:1)
要获得您想要的内容,您需要进行两项更改:
this
进行同步。run
的循环之外,以便一个线程在另一个线程进入之前完成整个循环。以下是NewThreadt类的修改版本:
class NewThreadt extends Thread {
private static Object lock = new Object();
void dota(int a) {
System.out.println(a);
}
// This is the entry point for the second thread.
public void run() {
synchronized (lock) {
try {
for (int i = 5; i > 0; i--) {
dota(i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
System.out.println(Thread.currentThread());
}
}
}