java線程同步實踐

    主線程輸出10個數,子線程輸出100個數,主線程循環輸出10個數..........循環50次。


package Threadtest;

public class testMain {


    public static void main(String[] args) {


        // 在內部類裏訪問局部變量printUtil,需要加 final
        final PrintUtil printUtil = new PrintUtil();


        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    printUtil.hundredPrint(i);
                }
            }
        }).start();
        
        for (int i = 0; i < 50; i++) {
            printUtil.tenPrint(i);
        }   


    }
}


class PrintUtil {
    //線程間通信信號,默認主線程執行
    private boolean signal=true;
    
    public synchronized void tenPrint(int count){
        if(!signal){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(count + "-------主線程第" + count + "次循環-------" + count);
        for (int i = 0; i < 10; i++) {
            System.out.println("ten print of:" + i);
        }
        signal=false;
        this.notify();


    }
    public synchronized void hundredPrint(int count){
        if(signal){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(count + "-------子線程第" + count + "次循環-------" + count);
        for (int i = 0; i < 100; i++) {
            System.out.println("hundred print of:" + i);
        }
        signal=true;
        this.notify();
        
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章