三种解题方法:
1
package com.dume.server.face;
/**
* 开启两个线程A、B,打印1到10,线程A打印奇数(1、3、5、7、9),线程B打印偶数(2、4、6、8、10)。
*/
public class ThreadA implements Runnable{
//最大数
private int max;
//打印方法的类
private Printer printer;
//是否偶数
private boolean isEventNumber;
public ThreadA(int max, Printer printer, boolean isEventNumber) {
this.max = max;
this.printer = printer;
this.isEventNumber = isEventNumber;
}
@Override
public void run() {
//如果是偶数为2,不是则1
int number = isEventNumber ? 2:1;
//直到小于等于10不成立
while(number<=max){
if(isEventNumber){
//打印偶数
printer.printEvent(number);
}else{
//打印奇数
printer.printOdd(number);
}
//自增2
number+=2;
}
}
/**
* 打印方法
*/
static class Printer {
private volatile boolean isOdd;
//同步代码块
synchronized void printEvent(int number){
//偶数时
while (!isOdd){
try{
//暂停线程,释放对象锁
wait();
}catch (InterruptedException e){
Thread.currentThread().interrupt();
}
}
//打印该奇数
System.out.println(Thread.currentThread().getName()+":"+number);
isOdd=false;
//继续执行
notify();
}
synchronized void printOdd(int number){
//如果是奇数
while (isOdd){
try{
//暂停线程,释放对象锁
wait();
}catch (InterruptedException e){
Thread.currentThread().interrupt();
}
}
//打印该奇数
System.out.println(Thread.currentThread().getName()+":"+number);
//设置共享变量为奇数类型
isOdd=true;
//继续执行
notify();
}
}
public static void main(String[] args){
Printer printer = new Printer();
new Thread(new ThreadA(10,printer,false),"奇数").start();
new Thread(new ThreadA(10,printer,true),"偶数").start();
}
}
2
package com.dume.server.face;
//开启两个线程A、B,打印1到10,线程A打印奇数(1、3、5、7、9),线程B打印偶数(2、4、6、8、10)。
import java.util.concurrent.locks.LockSupport;
/**
* 线程1和2交替输出
*/
public class ThreadB {
static Thread thread1;
static Thread thread2;
public static void main(String[] args) {
thread1 = new Thread(()->{
for(int i=1;i<=9;i+=2){
System.out.println(Thread.currentThread().getName()+"--"+"奇数:"+i);
//释放线程2
LockSupport.unpark(thread2);
//锁住当前线程1
LockSupport.park();
}
},"线程1");
thread2 = new Thread(()->{
for(int i=2;i<=10;i+=2){
//锁住线程2
LockSupport.park();
System.out.println(Thread.currentThread().getName()+"--"+"偶数:"+i);
//释放线程1
LockSupport.unpark(thread1);
}
},"线程2");
thread1.start();
thread2.start();
}
}
3
package com.dume.server.face;
//开启两个线程A、B,打印1到10,线程A打印奇数(1、3、5、7、9),线程B打印偶数(2、4、6、8、10)。
import java.util.concurrent.locks.LockSupport;
/**
* 按照顺序执行
*/
public class ThreadC {
static Thread thread1;
static Thread thread2;
public static void main(String[] args){
thread1 = new Thread(()->{
for(int i=1;i<10;i+=2){
//阻塞线程1
LockSupport.park();
System.out.println(Thread.currentThread().getName()+"--"+"奇数:"+i);
//开始线程2
LockSupport.unpark(thread2);
}
},"线程1");
thread2 = new Thread(()->{
for(int i=2;i<=10;i+=2){
//开始线程2
LockSupport.unpark(thread1);
//阻塞线程2
LockSupport.park();
System.out.println(Thread.currentThread().getName()+"--"+"偶数:"+i);
}
},"线程2");
thread1.start();
thread2.start();
}
}