一道线程面试题
2019-06-19 本文已影响0人
cjxll
2个线程交替打印1-100内的数,线程A打印偶数,线程B打印奇数
打印结果如下:
A: 0
B: 1
A: 2
B: 3
A: 4
B: 5
......
实现代码
public class printNum{
public static void main(String[] args) {
ThreadPrintNum threadPrintNum = new ThreadPrintNum();
new Thread(() -> {
for (int i = 0; i <= 100; i += 2) {
threadPrintNum.printEven(i);
}
},"A").start();
new Thread(() -> {
for (int i = 1; i < 100; i += 2) {
threadPrintNum.printOdd(i);
}
},"B").start();
}
}
class ThreadPrintNum {
private int num = 1;
private ReentrantLock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
/**
* 打印偶数
* @param i
*/
public void printEven(int i){
lock.lock();
try {
if(num != 1){
condition1.await();
}
System.out.println(Thread.currentThread().getName() + ": " + i);
num = 2;
condition2.signal();
} catch (Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 打印奇数
* @param i
*/
public void printOdd(int i){
lock.lock();
try {
if (num != 2){
condition2.await();
}
System.out.println(Thread.currentThread().getName() + ": " + i);
num = 1;
condition1.signal();
} catch (Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}