两个线程轮流打印奇数和偶数,输入enter停止
解决思路:
- 使用lock,设置判断终止的标志位
- 使用lock,利用interrupt和isInterrupted实现中断
// 使用lock/synchronized,设置判断终止的标志位
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class printEO{
private Lock printLock = new ReentrantLock();
private volatile int num = 0;
private boolean flag = true;
void printOdd(){
while(flag){
try {
printLock.lock();
if(num % 2 == 0){
System.out.println(Thread.currentThread().getName() + ": " + num);
++num;
Thread.sleep(2000);
}
} catch (Exception e) {
//TODO: handle exception
} finally{
printLock.unlock();
}
}
}
void printEven(){
while(flag){
try {
printLock.lock();
if(num % 2 == 1){
System.out.println(Thread.currentThread().getName() + ": " + num);
++num;
Thread.sleep(2000);
}
} catch (Exception e) {
//TODO: handle exception
} finally{
printLock.unlock();
}
}
}
void setFlag(){
this.flag = false;
}
public static void main(String[] args) {
printEO p = new printEO();
Thread po = new Thread(() -> p.printOdd());
Thread pe = new Thread(() -> p.printEven());
po.start();
pe.start();
Scanner sc = new Scanner(System.in);
sc.nextLine();
sc.close();
p.setFlag();
}
}
// 使用lock,利用interrupt和isInterrupted实现中断
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class printEO{
private Lock printLock = new ReentrantLock();
private volatile int num = 0;
void printOdd2(){
while(!Thread.currentThread().isInterrupted()){
try {
printLock.lock();
if(num % 2 == 0){
System.out.println(Thread.currentThread().getName() + ": " + num);
++num;
Thread.sleep(2000);
}
} catch (InterruptedException e) {
//TODO: handle exception
Thread.currentThread().interrupt();
} finally{
printLock.unlock();
}
}
}
void printEven2(){
while(!Thread.currentThread().isInterrupted()){
try {
printLock.lock();
if(num % 2 == 1){
System.out.println(Thread.currentThread().getName() + ": " + num);
++num;
Thread.sleep(2000);
}
} catch (InterruptedException e) {
//TODO: handle exception
Thread.currentThread().interrupt();
} finally{
printLock.unlock();
}
}
}
public static void main(String[] args) {
printEO p = new printEO();
Thread po = new Thread(() -> p.printOdd2());
Thread pe = new Thread(() -> p.printEven2());
po.start();
pe.start();
Scanner sc = new Scanner(System.in);
sc.nextLine();
sc.close();
po.interrupt();
pe.interrupt();
}
}
结果展示: