JAVA,2個線程交替打印數字


代碼如下:

package com.java.day19ThreadLock;
// 2個線程交替打印數字,線程之間的通信,等待和喚醒
public class ThreadPrint {
    static int num = 0;

    public static void main(String[] args) {

        // 鎖對象
        Object obj = new Object();
        new Thread(){
            @Override
            public void run() {
                System.out.println("准備開始打印了...");
                while (true){
                    synchronized (obj){
                        try {
                            // 線程等待
                            obj.wait();
                            System.out.println(num);
                            num++;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }.start();


        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (obj){
                        System.out.println(num);
                        num++;
                        // 喚醒線程
                        obj.notify();
                    }
                }

            }
        }.start();
    }
}

運行如圖:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM