多線程 -- sleep()方法和wait()方法區別

多線程 -- sleep()方法和wait()方法區別 - Lai18.com IT技術文章收藏夾 http://www.lai18.com/content/1751290.html 

Java 線程 sleep wait 深入解析 Thread - Lai18.com IT技術文章收藏夾 http://www.lai18.com/content/2439587.html


如何理解sleep持有鎖,wait釋放鎖?

如果sleep出現在synchronize塊中,sleep之後線程依然佔有鎖,其他線程不能訪問synchronize塊的代碼或函數。

如果wait出現在synchoronize塊中,wait之後線程釋放鎖,其他線程可以訪問synchronize塊的代碼或函數

如下的程序執行結果如下:

窗口二---賣出20  time=1455509031298
窗口二---賣出19  time=1455509031299
窗口二---賣出18  time=1455509031315
窗口二---賣出17  time=1455509031332
窗口二---賣出16  time=1455509031348
窗口二---賣出15  time=1455509031349
窗口二---賣出14  time=1455509031350
窗口二---賣出13  time=1455509031351
窗口二---賣出12  time=1455509031352
窗口二---賣出11  time=1455509031353
窗口二---賣出10  time=1455509031354
窗口二---賣出9  time=1455509031355
窗口二---賣出8  time=1455509031356
窗口二---賣出7  time=1455509031357
窗口二---賣出6  time=1455509031358
窗口二---賣出5  time=1455509031359
窗口二---賣出4  time=1455509031360
窗口二---賣出3  time=1455509031361
窗口二---賣出2  time=1455509031362
窗口二---賣出1  time=1455509031363
窗口二---賣出0  time=1455509031364
窗口三---賣出0  time=1455509031365
窗口一---賣出0  time=1455509031366
窗口四---賣出0  time=1455509031367

package testSynchronized;

import java.nio.charset.MalformedInputException;

public class demo2 {

	public static void main(String[] args) {

		Ticket2 t = new Ticket2();
		Thread t1 = new Thread(t, "窗口一");
		Thread t2 = new Thread(t, "窗口二");
		Thread t3 = new Thread(t, "窗口三");
		Thread t4 = new Thread(t, "窗口四");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

class Ticket2 implements Runnable {
	private int ticket = 20;

	public void run() {
		synchronized (this) {
			while (true) {
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (ticket <= 0) {
					System.out.println(Thread.currentThread().getName()
							+ "---賣出" + ticket + "  time="
							+ System.currentTimeMillis());
					break;
				}
				System.out.println(Thread.currentThread().getName() + "---賣出"
						+ ticket-- + "  time=" + System.currentTimeMillis());
			}
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章