三个线程并发按照顺序打印数字,直觉是创建一个runnable任务,然后建三个线程去执行。通过加锁去实现打印的循序
public class Main {
//三个线程并发打印数字
public static void main(String[] args) {
Count count = new Count();
Thread thread1 = new Thread(count, "1");
Thread thread2 = new Thread(count, "2");
Thread thread3 = new Thread(count, "3");
thread1.start();
thread2.start();
thread3.start();
}
}
class Count implements Runnable {
int i = 1;
Object lock = new Object();
public void run() {
synchronized (lock) {
while (i < 100)
if (i % 3 + 1 == Integer.parseInt(Thread.currentThread().getName())) {
System.out.println(i++);
lock.notifyAll();//唤醒其他线程
} else {
try {
lock.wait();//该线程阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
截取0-10的输出
线程1 0
线程2 1
线程3 2
线程1 3
线程2 4
线程3 5
线程1 6
线程2 7
线程3 8
线程1 9