线程交替打印

2020-01-11  本文已影响0人  桂老七
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();

    }
}
上一篇 下一篇

猜你喜欢

热点阅读