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();
    }
}
原文地址:https://www.cnblogs.com/Iqiaoxun/p/5927827.html