1. 程式人生 > >JAVA#執行緒通訊'札記

JAVA#執行緒通訊'札記

 public static void main(String[] args) {
        Counting c=new Counting();
        Thread t1=new Thread(c);
        Thread t2=new Thread(c);
        t1.setName("AISong");
        t2.setName("KobeSong");
        t1.start();
        t2.start();
    }
}
class Counting implements Runnable {
    int i = 0;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();//notify()/notifyAll()  應用在同步程式碼塊中,喚醒一個/所有執行緒
                if (i < 24) {
                    i++;
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                } else
                    break;
                try {
                    wait();//應用在同步程式碼塊中,釋放當前鎖
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
AISong:1
KobeSong:2
AISong:3
KobeSong:4
AISong:5
KobeSong:6
AISong:7
KobeSong:8
AISong:9
KobeSong:10
AISong:11
KobeSong:12
AISong:13
KobeSong:14
AISong:15
KobeSong:16
AISong:17
KobeSong:18
AISong:19
KobeSong:20
AISong:21
KobeSong:22
AISong:23
KobeSong:24