其他分享
首页 > 其他分享> > 两个线程交替执行

两个线程交替执行

作者:互联网

package cn.jiedada.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

public class MyTest {

    public static void main(String[] args) {

        MyTest myThread = new MyTest();
        new Thread(){
            @Override
            public void run() {
                //synchronized需要锁住调用该类的notify对象
                synchronized (myThread){
                    for (int i=0;i<10;i++){
                        //先唤醒在wait
                        myThread.notify();
                        System.out.println("a");
                        try {
                            myThread.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                synchronized (myThread){
                    for (int i=0;i<10;i++){
                        myThread.notify();
                        System.out.println("b");
                        try {
                            myThread.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }.start();
    }

}

 

标签:java,synchronized,MyTest,void,交替,线程,import,执行,public
来源: https://www.cnblogs.com/xiaoruirui/p/15009205.html