java 中 的多线程

package wait;
/*线程同步涉及的 同步控制:
 * wait(); 使当前线程等待,不在争抢CPU,并释放同步代码块 或 同步方法的 锁
 * notify(); 唤醒  某一个  被 wait()的线程
 * notifyAll(); 唤醒所有  被 wait() 的线程
 * */
public class TestWait implements Runnable { //自定义类实现 Runnable 接口

    @Override//重写 run() 方法
    public void run() {
        for (int i = 0; i < 5; i++) {
            //同步代码块,是线程 同步进行(实质 被多个线程 依次访问,不能同时访问)
            synchronized (this) { 
                //System.out.println(Thread.currentThread().getName() + ":" + i);
                // 当 所有 线程中 i = 2 的时候,阻塞 当前线程
                if (i == 2) {
                    try {
                        wait();// 阻塞当前线程,并释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //当 第二个线程 i=1时, 唤醒 第一个 被阻塞的 进程
                if(i==1){
                    notify();
                }
                /*到这里 第一个进程 顺利结束 并 当 第一个进程  i=4时 ,唤醒 第二个被 阻塞的 进程
                 * */ 
                if(i==4){
                    notifyAll();
                }        
            }
            // 输出 当前进程 的名称 和 索引值
            System.out.println(Thread.currentThread().getName()+i);

        }
    }

    public static void main(String[] args) {
        TestWait tw = new TestWait(); //自定义类的 构造 方法
        // 通过 有参 构造方法 Thread(Runnable,target),将自定义 实现类 的对象 传入
        Thread th1 = new Thread(tw, "A");
        Thread th2 = new Thread(tw, "B");
        th1.start(); //调用start()方法,是线程 就绪
        th2.start();

    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42785557/article/details/82226438