美文网首页
两个线程严格交替执行java实现

两个线程严格交替执行java实现

作者: 会疼的小石头 | 来源:发表于2019-05-26 15:07 被阅读0次

public class ThreadTurn {

    Object o = new Object();

    Boolean f = true ; // True 时线程1执行

    class Thread1 extends Thread{

        public void run() {

            synchronized (o) {

                for (int i = 0; i < 100; i++) {

                    System.out.print("A线程--->"+i);

                    o.notify();

                    if(f){

                        f = false;

                        try{

                            o.wait();

                        }catch(Exception e){

                            System.out.print(e);

                        }

                    }

                }

            }

        }

    }

    class Thread2 extends Thread{

        public void run(){

            synchronized (o){

                for(int i=0;i<100;i++){

                    System.out.println(" B线程--->"+i);

                    o.notify();

                    if(!f){

                        f = true;

                        try {

                            o.wait();

                        }catch(Exception e){

                            System.out.print(e);

                        }

                    }

                }

            }

        }

    }

    public void start(){

        new Thread1().start();

        new Thread2().start();

    }

    public static void main(String args[]){

        ThreadTurn t = new ThreadTurn();

        t.start();

    }

}

相关文章

网友评论

      本文标题:两个线程严格交替执行java实现

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