zoukankan      html  css  js  c++  java
  • 多线程同步 wait notify

    package test;
    
    public class Test implements Runnable{
    
        public static int j =0;
        @Override
        public void run() {
                synchronized (this) {
                    while (j<30) {
                        System.out.println(Thread.currentThread().getName() + ": " + ++j);  
                        if (j % 3 == 0 && 0 != j) {
                            try {
                                this.notify(); // 唤醒另外一个线程  
                                this.wait(); // 暂时释放资源  
                            } catch (InterruptedException e) {
                                e.printStackTrace();  
                            } 
                        }
                    }
                }
        }
        public static void main(String[] args) {
            Runnable run = new Test();
            Thread thread1 = new Thread(run);
            Thread thread2 = new Thread(run);
            
            thread1.start();
            thread2.start();
        }
    }
    Thread-1: 1
    Thread-1: 2
    Thread-1: 3
    Thread-0: 4
    Thread-0: 5
    Thread-0: 6
    Thread-1: 7
    Thread-1: 8
    Thread-1: 9
    Thread-0: 10
    Thread-0: 11
    Thread-0: 12
    Thread-1: 13
    Thread-1: 14
    Thread-1: 15
    Thread-0: 16
    Thread-0: 17
    Thread-0: 18
    Thread-1: 19
    Thread-1: 20
    Thread-1: 21
    Thread-0: 22
    Thread-0: 23
    Thread-0: 24
    Thread-1: 25
    Thread-1: 26
    Thread-1: 27
    Thread-0: 28
    Thread-0: 29
    Thread-0: 30

    简单的多线程同步的例子,理解:

    Thread0先获得对象锁this,THread1在等待,当Thread0进入this.notify(); // 唤醒另外一个线程  此行时,唤醒Thread1,但由于Thread0仍然占据着this对象锁,Thread1还不会进入同步代码块,直到Thread0运行到this.wait(),此时Thread0释放this对象锁,堵塞,Thread1获得对象锁,进入同步代码块,循环...

  • 相关阅读:
    x+=y与x=x+y有什么区别?
    Linux下带宽流量工具iftop实践
    使用pinyin4j实现汉字转拼音
    Spring整合Velocity模版引擎
    Json工具类库之Gson实战笔记
    腾讯移动分析 签名代码示例
    Docker搭建Portainer可视化界面
    maven 打包 spring boot 生成docker 镜像
    Mysql 为什么要选择 B+Tree
    idea 添加 注释 配置
  • 原文地址:https://www.cnblogs.com/fengjian/p/3724977.html
Copyright © 2011-2022 走看看