zoukankan      html  css  js  c++  java
  • java多线程学习-同步之线程通信

    这个示例是网上烂大街的,子线程循环100次,主线程循环50次,但是我试了很多次,而且从网上找了很多示例,其实多运行几次,看输出结果并不正确。不知道是我转牛角尖了,还是怎么了。也没有大神问,好痛苦。现在记录在这里,等以后有时间看。

    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class ThreadCommunication {
        public static void main(String[] args) {
            final Test2 t = new Test2();
            new Thread(new Runnable() {
                public void run() {
                    for(int i=0;i<10;i++){
                        t.sub(i);
                    }
                }
            }).start();
            
            for(int i=0;i<10;i++){
                t.main(i);
            }
            
        }
    }
    
    class Test{
        
        boolean isSub = false;
        
        public synchronized void sub(int l){
            System.out.println("-----sub");
            while(!isSub){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
            for(int i=0;i<10;i++){
                System.out.println(l+" sub "+i);
            }
            isSub = false;
            this.notify();
        }
        
        public synchronized void main(int l){
            System.out.println("-----main");
            while(isSub){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
            for(int i=0;i<10;i++){
                System.err.println(l+" main "+i);
            }
            isSub = true;
            this.notify();
        }
    }
  • 相关阅读:
    task-clph
    遍历数组的方式
    iOS事件处理之七种手势
    quatz2d使用注意点
    iOS 细碎知识整理
    九宫格算法图示
    mac10.12的Cocopods安装使用
    静态库冲突的解决办法:duplicate symbol
    ceshi
    xmpp4-总览
  • 原文地址:https://www.cnblogs.com/Iqiaoxun/p/5927827.html
Copyright © 2011-2022 走看看