多线程面试题
两个线程一个打印奇数一个打印偶数
private int count = 0;
private final Object lock = new Object();
@Test
public void test() throws InterruptedException {
Thread even = new Thread(new TurningRunner(), "偶数");
even.start();
// 确保偶数线程线先获取到锁
Thread.sleep(1);
Thread odd = new Thread(new TurningRunner(), "奇数");
odd.start();
even.join();
odd.join();
}
class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
lock.notifyAll();
try {
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}N个线程顺序循环打印从0至100
synchornized锁住的是什么
阻塞队列实现生产者消费者模型
手写生产者消费者模型
Last updated