我使用synchronized
为了执行第一个线程,然后在第一个线程完成时执行另一个线程,但是两个线程同时执行。为什么?
public class PrintNums extends Thread {
int num;
public PrintNums(int x) {
this.num = x;
}
@Override
public void run() {
this.count();
}
public synchronized void count() {
for (int i = 1; i <= 5; i++) {
System.out.println((2 * i - this.num));
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException ex) {
}
}
}
public static void main(String[] args) {
PrintNums odd = new PrintNums(1);
PrintNums even = new PrintNums(0);
odd.start();
even.start();
}
}
最佳答案
没有显式目标的
synchronized
意味着 synchronized(this)
:每个线程都在自身同步,因此不存在冲突。如果你想序列化它们,你可以使用synchronized(PrintNums.class)
。
请注意,通常有比使用显式线程更好的构造,例如执行器或闩锁。
关于java - 为什么当我使用 'synchronized' 时我的线程没有一个接一个地执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556835/