1. 程式人生 > 實用技巧 >執行緒通訊

執行緒通訊

1.執行緒通訊的方法

wait()、notify()、notifyAll()

2.說明

1.wait()、notify()、notifyAll()三個方法必須使用在同步程式碼塊或同步方法中。
2.wait()、notify()、notifyAll()三個方法的呼叫者必須是同步程式碼塊或同步方法
    中的同步監視器(鎖)
3.wait()、notify()、notifyAll()三個方法是定義在java.lang.Object類中的

3.例子(使用執行緒通訊實現交替買票)

public class App {
    public static void main(String[] args) throws
Exception { sellTicket s = new sellTicket(); Thread t1 = new Thread(s); Thread t2 = new Thread(s); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); } } class sellTicket implements Runnable { private int num = 100; @Override
public void run() { while (true) { synchronized (this) { this.notify();//對應說明中的第二條規則 if (num > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()
+ "購買了第" + num + "張票"); num--; try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ break; } } } } }