线程交替打印

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();

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容