我有一个问题,我必须以这种格式打印数字。
First 1
First 2
Second 3
Second 4
First 5
First 6
Second 7
Second 8
First 9
and so on...
我已经实现了我的可运行接口,如下所示。
class ThreadDemo implements Runnable {
public volatile Integer num;
public Object lock;
public ThreadDemo(Integer num, Object lock) {
this.num = num;
this.lock = lock;
}
@Override
public void run() {
try {
while (true) {
int count = 0;
synchronized(lock) {
Thread.sleep(100);
while (count < 2) {
System.out.println(Thread.currentThread().getName() + " " + num++);
count++;
}
lock.notify();
lock.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我的主要课程如下
public class CoWorkingThreads {
private static volatile Integer num = new Integer(1);
public static void main(String...args) {
Object lock = new Object();
Thread thread1 = new Thread(new ThreadDemo(num, lock), "First");
thread1.start();
Thread thread2 = new Thread(new ThreadDemo(num, lock), "Second");
thread2.start();
}
}
当我运行程序时,我得到如下输出
First 1
First 2
Second 1
Second 2
First 3
First 4
Second 3
Second 4
而不是之前预期的结果。但是当我将整数更改为原子整数类型时,我开始得到预期的结果。谁能解释我可以做些什么来使它使用整数而不是使用原子整数运行
慕慕森
胡子哥哥
缥缈止盈
相关分类