Java多线程wait,notify与part,unpart的区别

Java多线程wait,notify与park,unpark的区别:

1:wait和notify是有先后顺序的,而part和unpark没有先后顺序

代码如下:

package com.wait.test;

public class WaitAndNotifyTest {
	public static void main(String[] args) {
		System.out.println("约女朋友吃饭开始");
		Object o = new Object();
		Runnable gg = new Runnable(){
			@Override
			public void run() {
				try {
					System.out.println("GG:已经到达指定餐馆");
					synchronized (o) {
						o.wait();
					}
					System.out.println("GG:遇到了MM,开始一起去吃饭");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Thread ggThread = new Thread(gg);
		ggThread.start();
		Runnable mm = new Runnable(){
			@Override
			public void run() {
				System.out.println("MM:已经到达指定餐馆");
				synchronized (o) {
					o.notify();
				}
			}
		};
		new Thread(mm).start();;
	}

}

以上代码的执行结果:


但是如果GG有事情,耽误了一秒钟,这样可能失去美好的烛光晚餐。代码如下:

package com.wait.test;


public class WaitAndNotifyTest {
	public static void main(String[] args) {
		System.out.println("约女朋友吃饭开始");
		Object o = new Object();
		Runnable gg = new Runnable(){
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					System.out.println("GG:已经到达指定餐馆");
					synchronized (o) {
						o.wait();
					}
					System.out.println("GG:遇到了MM,开始一起去吃饭");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Thread ggThread = new Thread(gg);
		ggThread.start();
		Runnable mm = new Runnable(){
			@Override
			public void run() {
				System.out.println("MM:已经到达指定餐馆");
				synchronized (o) {
					o.notify();
				}
			}
		};
		new Thread(mm).start();;
	}


}

上面的代码,加上了Thread.sleep(1000);执行结果如下(无限等待下去了-死锁):


2:我把wait和notify换成,part和unpart效果如下:

package com.wait.test;

import java.util.concurrent.locks.LockSupport;

public class ParkAndUnparkTest {
	public static void main(String[] args) {
		System.out.println("约女朋友吃饭开始");
		Runnable gg = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					System.out.println("GG:已经到达指定餐馆");
					LockSupport.park(this);
					System.out.println("GG:遇到了MM,开始一起去吃饭");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Thread ggThread = new Thread(gg);
		ggThread.start();
		Runnable mm = new Runnable() {
			@Override
			public void run() {
				System.out.println("MM:已经到达指定餐馆");
				LockSupport.unpark(ggThread);
			}
		};
		new Thread(mm).start();
	}

}

执行结果(这个时候女朋友比较理解男孩,一起享受了烛光晚餐的浪漫):


猜你喜欢

转载自blog.csdn.net/qq_33820379/article/details/80636611