`

简单的多线程正确打印AB(打印乒乓)

阅读更多
import java.util.concurrent.Executor;  
    import java.util.concurrent.Executors;  
      
      
    public class AB {  
       public static String s="";  
        public static void main(String[] args) {  
      
             Executor e=Executors.newFixedThreadPool(2); //最多两个同时运行的线程池  
            e.execute(new Runnable(){  
                public void run(){  
                    synchronized(s){  
                        while(true){            //死循环 一直打印A吧  
                     System.out.print("A");  
                     try {    
                                        s.wait();               //等待  
                                s.notify();            //有则唤醒 这些都要s来完成                           
                    } catch (InterruptedException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                        }  
                    }  
                    }  
                  
            });  
      
            e.execute(new Runnable(){  
                public void run(){  
                    synchronized(s){  
                        while(true){  
                     System.out.print("B");  
                     try {  
                         s.notify();                    //唤醒打印A的线程  
                        s.wait(1000);              //自己则等待  
                    } catch (InterruptedException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                        }  
                    }  
                }  
                  
            });  
        }  
      
    }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics