美文网首页
线程交替打印

线程交替打印

作者: 桂老七 | 来源:发表于2020-01-11 23:32 被阅读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();

    }
}

相关文章

网友评论

      本文标题:线程交替打印

      本文链接:https://www.haomeiwen.com/subject/omtiactx.html