線程交替打印

public class jiaoti {
    public static void main(String[] args) throws InterruptedException {
        int[] aaa={1,3,5};
        int[] bbb={2,4,6};
        Queue<Integer> sa = new LinkedList<Integer>();
        Queue<Integer> sb = new LinkedList<Integer>();
        for(int i=0;i<aaa.length;i++){
            sa.offer(aaa[i]);
        }
        for(int i=0;i<bbb.length;i++){
            sb.offer(bbb[i]);
        }


        // 不加鎖用CAS形式
        AtomicInteger k=new AtomicInteger(0);
        Thread a =new Thread(()->{
            while (sa.size()>0){
                while(!k.compareAndSet(0,1)){
                }
                System.out.println(sa.poll());
                while(!k.compareAndSet(1,2)){
                }
            }
        });
        Thread b=new Thread(()->{
            while (sb.size()>0){
                while(!k.compareAndSet(2,3)){
                }
                System.out.println(sb.poll());
                while(!k.compareAndSet(3,0)){
                }

            }
        });

        a.start();
        b.start();
        b.join();
        System.out.println("finished");


        for(int i=0;i<aaa.length;i++){
            sa.offer(aaa[i]);
        }
        for(int i=0;i<bbb.length;i++){
            sb.offer(bbb[i]);
        }
  
        // 加鎖形式:synchronized(obj)+obj.wait()+obj.notify()
        Object obj=new Object();
        Thread c =new Thread(()->{
            while (sa.size()>0){
                synchronized (obj){
                    System.out.println(sa.poll());
                    try {
                        obj.notify();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread d=new Thread(()->{
            while (sb.size()>0){
                synchronized (obj){
                    System.out.println(sb.poll());
                    try {
                        obj.notify();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

        c.start();
        Thread.sleep(100);
        d.start();

    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容