LockSupport和synchronized混合死鎖問題

我來濫竽充數一篇文章,LockSupportsynchronized果真不能混着用,直接形成死鎖。java

package test;

import java.util.concurrent.locks.LockSupport;

/**
 * @author Wei.Chou(weichou2010@gmail.com)
 * @version 1.0, 12/08/2016
 */
public class ParkTest {
    public static void main(String[] args) {
        final Thread thread = new Thread() {
            @Override
            public void run() {
                System.out.println("thread started");
                synchronized (ParkTest.class) {
                    System.out.println("thread park");
                    LockSupport.park();
                    System.out.println("thread release");
                }
            }
        };
        thread.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread() {
            @Override
            public void run() {
                System.out.println("thread1 started");
                // TODO: 16/8/12 果真死鎖
                synchronized (ParkTest.class) {
                    System.out.println("thread1 unpark");
                    LockSupport.unpark(thread);
                    System.out.println("thread1 end");
                }

            }
        }.start();
    }
}
相關文章
相關標籤/搜索