zoukankan      html  css  js  c++  java
  • 线程间通讯

    /**
     *将线程要运行的逻辑代码及数据同步相关的锁,放在同一个类中,这里是Business类,数据同步由Business类维护
     *而与线程控制相关的代码分开,指的是线程类本身
     *
     */
    public class CommunicationTest {
    
        public static void main(String[] args) {
    
            Business business = new Business();
    
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    for (int i = 1; i <= 50; i++) {
                        business.main(i);
                    }
                }
            }).start();
    
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    for (int i = 1; i <= 50; i++) {
                        business.sub(i);
                    }
                }
            }).start();
    
        }
    
    }
    
    class Business {
        
        private boolean isShouldSub = false;
    
        public synchronized void sub(int i) {
            while (!isShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int j = 1; j <= 10; j++) {
                System.out.println("sub thread sequence of  " + j + " , loop of " + i);
            }
            isShouldSub = false;
            this.notify();
        }
    
        public synchronized void main(int i) {
            while (isShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int j = 1; j <= 30; j++) {
                System.out.println("main thread sequence of  " + j + " , loop of " + i);
            }
            isShouldSub = true;
            this.notify();
        }
    }
  • 相关阅读:
    库函数(汇总)
    IE jQuery ajax 请求缓存问题
    Jarvis OJ-level3
    在64位的linux中运行32位的应用程序
    ROP之linux_x64知识杂记
    2017年网络空间安全技术大赛部分writeup
    Sniper OJ部分writeup
    gdb插件使用方法
    pwntools学习
    linux虚拟机安装值得注意的几点
  • 原文地址:https://www.cnblogs.com/moris5013/p/11707764.html
Copyright © 2011-2022 走看看