如何让两个线程交替执行

public class Test07 {

volatile boolean flag = false;

public static void main(String[] args) {

    Test07 t7 = new Test07();


    new Thread(()->{
        int i = 65;
        while(i < 85){
            synchronized (t7){
                try{
                    if(t7.flag){
                        System.out.println((char)i);
                        i++;
                        t7.flag  = !t7.flag;
                        t7.notify();
                    }else{
                        t7.wait();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }).start();


    new Thread(()->{
        int i = 0;
        while( i < 20){
           synchronized (t7){
               try{
                   if(t7.flag){
                     t7.wait();
                   }else{
                       System.out.println(i);
                       i++;
                       t7.flag  = !t7.flag;
                       t7.notify();
                   }
               }catch (Exception e){
                   e.printStackTrace();
               }
           }
        }
    }).start();


}

}

你可能感兴趣的:(java)