两个线程循环打印奇偶数

package com.jiading;

/**
 * 两个线程循环打印奇偶数
 */
public class PrintTest {
    //flag必须是外部公共资源,也就是外部类的类变量
    public boolean flag;
    public class JiClass implements Runnable{
        public PrintTest t;
        public JiClass(PrintTest t){
            //使用外部类对象作为锁
            this.t=t;
        }
        @Override
        public void run(){
            int i=1;
            while(i<100){
                synchronized (t){
                    //虽然有可能一个线程连续两次抢到锁,但是因为flag已经变了,所以还是要到else中wait
                    if(!t.flag){
                        System.out.println(i);
                        i+=2;
                        t.flag=true;
                        t.notify();
                    }else{
                        try{
                            t.wait();//wait t 这个锁
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    public class OuClass implements Runnable{
        public PrintTest t;
        public OuClass(PrintTest t){
            this.t=t;
        }
        @Override
        public void run(){
            int i=2;
            while(i<100){
                synchronized (t){
                    if(t.flag){
                        System.out.println(i);
                        i+=2;
                        t.flag=false;
                        t.notify();
                    }else{
                        try{
                            t.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        //先创建一个外部类对象
        PrintTest tt=new PrintTest();
        //要想直接创建内部类的对象,必须使用外部类的对象来创建内部类对象
        JiClass jiClass=tt.new JiClass(tt);
        OuClass ouClass=tt.new OuClass(tt);
        new Thread(jiClass).start();
        new Thread(ouClass).start();
    }
}
posted @ 2020-03-17 20:59  别再闹了  阅读(647)  评论(0)    收藏  举报