java多執行緒學習小案例

weixin_34150503發表於2017-11-29

多執行緒的小練習

需求:實現一次修改一次輸出

主要知識點:多執行緒,同步,等待和喚醒


public class inAndOut {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        // 1、兩個執行緒控制同一個物件      引數傳入
        // 2、同步    變性問題(賦值到一半就輸出了)         
        // 3、一次修改一次輸出  wait 和 notify
        
        
        Test tt = new Test();   // 給兩個不同現成提供同一個物件
        In in = new In(tt);
        Out out = new Out(tt);
        Thread ti = new Thread(in);
        Thread to = new Thread(out);
        ti.start();
        to.start();
    }

}
class In implements Runnable{
    private Test r;
    private boolean a = true;
    
    @Override
    public void run() {
        
        while(true){
            synchronized (r) {  //處理變性問題
                if(r.b){   // 修改為一條輸出一條  現成的等待和喚醒                in執行時,out等待。  執行完後喚醒,out執行,in等待。。。。
                    if(a){  // 模擬不同的輸入
                        r.name = "zhangsan";
                        r.sex = "nan";
                        a = false;
                    }else{
                        r.name = "lisi";
                        r.sex = "nv";
                        a=true;
                    }
                    r.b=false;
                    r.notify();  // 喚醒程式
                    
                }else{
                    try {
                        r.wait();  //當前程式等待
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    In(Test r){
        this.r = r;
    }
    
}
class Out implements Runnable{
    private Test r;
    @Override
    public void run() {
        while(true){
            synchronized (r) {
                if(!r.b){
                    System.out.println(r.name+"..."+r.sex);
                    r.b = true;
                    r.notify();
                }else{
                    try {
                        r.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    Out(Test r){
        this.r = r;
    }
    
}
class Test{
    String name;
    String sex;
     boolean b = true;
}

相關文章