三個線程交替打印1到100


public class Test {
    volatile int i = 1;

    public static void main(String[] args) throws Exception {
        Test obj = new Test();


        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (obj.i <= 100) {
                    // 上鎖當前對象
                    synchronized (this) {

                        // 喚醒另一個線程
                        notifyAll();
                        if (obj.i == 101) {
                            return;
                        }

                        int i = new Integer(Thread.currentThread().getName());
                        if (obj.i % 3 == i) {
                            System.out.println("Thread " + Thread.currentThread().getName() + " " + obj.i++);
                        }
                        if(obj.i % 3==1){
                            System.out.println("==========");
                        }
                        try {
                            if (obj.i == 101) {
                                notifyAll();
                                return;
                            } else {
                                // 釋放掉鎖
                                wait();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        // 啟動多個線程(想創建幾個就創建幾個)
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        Thread t3 = new Thread(runnable);

        t1.setName("1");
        t2.setName("2");
        t3.setName("0");
        t1.start();
        t2.start();
        t3.start();


    }


}

 


免責聲明!

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



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