关于LockSupport交替打印字符串发现的一个小问题
程序员文章站
2022-05-01 22:52:08
...
写个最简单的Demo,说明一下啥问题
import java.util.concurrent.locks.LockSupport;
public class Test {
static class ThreadA extends Thread{
@Override
public void run() {
System.out.println("----------before park method");
LockSupport.park();
System.out.println("----------after park method");
}
}
static class ThreadB extends Thread{
private Thread thread;
public void setThread(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
System.out.println("----------before unpark method");
LockSupport.unpark(thread);
System.out.println("----------afeter unpark method");
}
}
public static void main(String[] args) {
ThreadB threadB = new ThreadB();
ThreadA threadA = new ThreadA();
threadB.setThread(threadA);
threadB.start();
threadA.start();
}
}
线程B里面持有线程A引用,线程A调park方法阻塞,线程B调unpark方法将线程A唤醒。
测试结果:
----------before unpark method
----------before park method
----------afeter unpark method
----------after park method
从测试结果上面来看,这个方法貌似没有任何问题。
但是如果你将断点打在threadA.start();这一行,在调试状态下,当程序执行到这行时,线程B方法都已执行完毕,此时线程A尚未调用start()方法,你发现此时线程A就永久阻塞park()方法上了。
所以正确的方法应该是先调用线程A的start()方法,然后再调用线程B的start()方法.
同理由此看一下交替打印字符串的方法:
import java.util.concurrent.locks.LockSupport;
public class LockSupportPrint {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
ThreadB threadB = new ThreadB();
threadA.setLockThread(threadB);
threadB.setLockThread(threadA);
threadA.start();
threadB.start();
}
static class ThreadA extends Thread {
private Thread lockThread;
public void setLockThread(Thread lockThread) {
this.lockThread = lockThread;
}
@Override
public void run() {
for (int i = 0; i <= 9; i++) {
System.out.print(i);
LockSupport.unpark(lockThread);
LockSupport.park();
}
}
}
static class ThreadB extends Thread {
private Thread lockThread;
public void setLockThread(Thread lockThread) {
this.lockThread = lockThread;
}
@Override
public void run() {
for (int i = 0; i <= 9; i++) {
LockSupport.park();
System.out.print((char)(65 + i));
LockSupport.unpark(lockThread);
}
}
}
}
多跑几次,你可能会得到一样结果并且程序能正常的结束,但是如果你把main方法改成下面的方法,并且让循环的次数尽可能的大,你最终发现如同上面的情况,park()方法没有被唤醒。
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i <= 1000000; i++) {
ThreadA threadA = new ThreadA();
ThreadB threadB = new ThreadB();
threadA.setLockThread(threadB);
threadB.setLockThread(threadA);
threadA.start();
threadB.start();
threadA.join();
threadB.join();
System.out.println();
}
}
所以正确的打开方式应该是先start 调用park方法的线程,然后start调用unpark方法的线程。
上一篇: 关于单链表逆序的一个小问题