两个线程交替执行

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();
    }

}

 

上一篇:.Net Core 控制台应用程序 依赖注入


下一篇:20210622PHP