题目链接leetcode 这种多线程题总是很难在本地验证 然后打断点来排错,下面提供一下此题的本地实现方法 废话不多说 上代码
1.先自定义一个需要的工具类
import java.util.function.IntConsumer;
public class myIntConsumer implements IntConsumer {
@Override
public void accept(int value) {
System.out.println(value);
}
}
2.然后上主类 顺便提供了semaphore的解法
import java.util.concurrent.Semaphore;
public class lk1116 {
Semaphore zero = new Semaphore(1);
Semaphore even = new Semaphore(0);
Semaphore odd = new Semaphore(0);
private int n;
public volatile int x = 0;
public lk1116(int n) throws InterruptedException {
System.out.println("创建对象了");
this.n = n;
new Thread(() -> {
try {
zero(new myIntConsumer());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
,"零").start();
new Thread(() -> {
try {
even(new myIntConsumer());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
,"偶").start();
new Thread(() -> {
try {
odd(new myIntConsumer());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
,"奇").start();
}
public void zero(myIntConsumer printNumber) throws InterruptedException {
System.out.println("进来了零方法");
while (x < n) {
zero.acquire();
printNumber.accept(0);
x++;
if ((x & 1) == 1) {
odd.release();
}else even.release();
}
printNumber.accept(n);
if ((n&1)==1){
even.release();
}else odd.release();
}
public void even(myIntConsumer printNumber) throws InterruptedException {
while (x < n) {
even.acquire();
if (x!=n) printNumber.accept(x);
zero.release();
}
}
public void odd(myIntConsumer printNumber) throws InterruptedException {
while (x < n) {
odd.acquire();
if (x!=n) printNumber.accept(x);
zero.release();
}
}
}
3.调用
public static void main(String[] args) throws InterruptedException {
lk1116 lk1116 = new lk1116(5);
}
最后打印 最后这种多线程打断点一定要将断点改为线程级别的,如下图为IDEA修改断点为线程级 然后线程间切换使用以下方式切换
|