1、题目
两个线程,一个负责打印1,3,5.。。。99;
另一个负责打印2,4,6,。。。100;
要交替进行,最后打印出来的次序是1,2,3,4,5,6,。。。99,100
2、分析
使用java.util.concurrent.locks.ReentrantLock;
分析,这里涉及 两个线程的同步,需要用到signal/await;
可以利用并发工具类ReentrantLock,结合这个锁所产生的Condition对象,每个线程各有一个Condition;
3、上代码
package com.hst.ces;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author :zy
* @date :Created in 2022/07/06 18:06
* @description:描述
* @version: 1.0
*/
public class Learning {
static Lock lock = new ReentrantLock();
//线程并发库中用于线程之间通讯的类相当于wait(),notify()
static Condition condOdd = lock.newCondition();
static Condition condEven = lock.newCondition();
static volatile boolean bPrintOdd = true; //优先打印奇数
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
threadPrintEven();
}
}).start();
//let sub-thread started first (这个延迟,无所谓,只是表明奇数线程先执行还是后执行都可以保证结果符合预期)
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
threadPrintOdd();
}
private static void threadPrintOdd() {
lock.lock();
System.out.println("odd enter lock ");
try {
for (int i = 1; i < 100; i += 2) {
if (!bPrintOdd) {
//唤醒一个等待的线程
condEven.signal();
System.out.println("odd signal then wait");
//让当前线程进行等待
condOdd.await();
}
System.out.println(i);
bPrintOdd = false;
}
//唤醒另一个线程,打印最后一个偶数
if (!bPrintOdd) {
condEven.signal();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("odd finished");
}
private static void threadPrintEven() {
lock.lock();
System.out.println("even enter lock");
try {
for (int i = 2; i <= 100; i += 2) {
if (bPrintOdd) {
//唤醒一个等待的线程
condOdd.signal();
System.out.println("even signal then wait");
//让当前线程进行等待
condEven.await();
}
System.out.println(i);
bPrintOdd = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("even finished");
}
}