线程交替打印

public class jiaoti {
    public static void main(String[] args) throws InterruptedException {
        int[] aaa={1,3,5};
        int[] bbb={2,4,6};
        Queue sa = new LinkedList();
        Queue sb = new LinkedList();
        for(int i=0;i{
            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{
            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();

    }
}

你可能感兴趣的:(线程交替打印)