两个线程交替打印数字到100

1、等待唤醒机制

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author: surepeng
 * @description:
 * @date: 2019/07/24
 **/
public class MultiThreadPrint {
    static MultiThreadPrint instance = new MultiThreadPrint();
    static int i = 1;
    Thread t1 = new Thread() {
       
        @Override
        public void run() {
            while (i <= 100) {
                synchronized (instance) {
                    try {
                        instance.notify();
                        System.out.println(i++);
                        System.out.println(Thread.currentThread().getName());
                        instance.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    };

    Thread t2 = new Thread() {

        @Override
        public void run() {
            while (i <= 100) {
                synchronized (instance) {
                    try {
                        instance.notify();
                        System.out.println(i++);
                        System.out.println(Thread.currentThread().getName());
                        instance.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }
    };

    public static void main(String[] args) {
        MultiThreadPrint multi = new MultiThreadPrint();
        ExecutorService exe = Executors.newFixedThreadPool(2);
        exe.submit(multi.t1);
        exe.submit(multi.t2);
    }
}

2、pv信号量(Semaphore)

//TODO

你可能感兴趣的:(java并发编程)