public class PrintNum {
public static void main(String[] args) {
Task task = new Task();
Thread thread1 = new Thread(task);
thread1.setName("thread1");
Thread thread2 = new Thread(task);
thread2.setName("thread2");
thread1.start();
thread2.start();
}
}
class Task implements Runnable{
private volatile boolean flag = false;
private volatile int count = 0;
@Override
public void run() {
while (true){
if ("thread1".equals(Thread.currentThread().getName()) && !flag && count < 10){
System.out.println(Thread.currentThread().getName() + "打印数字" + count++);
flag = true;
}
if ("thread2".equals(Thread.currentThread().getName()) && flag && count < 10){
System.out.println(Thread.currentThread().getName() + "打印数字" + count++);
flag = false;
}
}
}
}
结果
thread1打印数字0
thread2打印数字1
thread1打印数字2
thread2打印数字3
thread1打印数字4
thread2打印数字5
thread1打印数字6
thread2打印数字7
thread1打印数字8
thread2打印数字9
这篇博客展示了如何使用多线程让两个线程交替打印数字,从0到9,详细记录了每个线程打印的数字顺序。
249

被折叠的 条评论
为什么被折叠?



