美文网首页
线程交替题目

线程交替题目

作者: 咚了个汐 | 来源:发表于2018-09-20 14:47 被阅读22次
    package dong;
    public class WaitAndNotify {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            final Temp temp = new Temp();
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    for (int i = 1; i <= 50; i++) {
                        temp.sub(i);
                    }
                }
            }).start();
            for (int i = 1; i <= 50; i++) {
                temp.main(i);
            }
            
        }
        
    
    }
    class Temp {
        private boolean flag = true;
        public synchronized void main(int j){
            if (flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int i = 1; i <= 100; i++) {
                System.out.println("main=="+j+"==="+i+"===="+Thread.currentThread().getName());
            }
            flag = true;
    //      flag = !flag;
            notify();
        }
        public synchronized void sub(int j){
            if (!flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println("sub++++"+j+"+++++"+i+"++++++++++++"+Thread.currentThread().getName());
            }
            flag = false;
    //      flag = !flag;
            notify();
        }
    }

    相关文章

      网友评论

          本文标题:线程交替题目

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