一个线程 +1 一个线程 -1 默认初始值为0 循环10次 输出:01010101
今天看一些面试题,有一道关于多线程的题。分析了一下:主要考察多线程synchronized(),wait(),notifyAll()
代码:
TestThread.class
/**
* 要求:一个线程 +1 一个线程 -1 默认初始值为0 循环10次 输出:01010101
*
*/
class TestThread implements Runnable {
int i = 1;
int count = 1;
boolean b = true;
@Override
public void run() {
while (b) {
if (count <= 10){
synchronized (this) {
notify();
try {
//Thread.currentThread();
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 0) {
i++;
System.out.print(i);
count++;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
i--;
System.out.print(i);
count++;
}
}
}else {
break;
}
}
}
}
demo2.class
public class demo2 {
public static void main(String[] args) {
/*只有一个TestThread对象*/
TestThread t = new TestThread();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}
现象:虽然按要求输出结果,但是程序无法结束,并不是2个线程交互进行。而是在争夺CPU资源
后来我把线程名放到输出语句后发现其实是两个线程在争夺CPU资源。并不是交替输出0和1
我猜想可能是锁的方式不对导致2个进程同时进入锁中争夺CPU资源最后无法出去,程序也无法结束。
修改后代码:
LastThread.class
public class LastThread {
private int num = 0;
public synchronized void add() throws InterruptedException {
//判断
while (num != 0){
this.wait();
}
//操作
System.out.print(num);
num++;
//通知唤醒
this.notifyAll();
}
public synchronized void sub() throws InterruptedException {
//判断
while (num == 0){
this.wait();
}
//操作
System.out.print(num);
num--;
//通知唤醒
this.notifyAll();
}
}
LastDemo.class
public class LastDemo {
public static void main(String[] args){
LastThread lastThread = new LastThread();
new Thread(() -> {
for (int i = 0;i <= 10;i++){
try {
lastThread.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 0;i <= 10;i++){
try {
lastThread.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
修改后实现要求