线程部分注意点

2017-09-11  本文已影响0人  Eve0
public class ThreadTest2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PPNums pNum = new PPNums();
        TThread t1 = new TThread(pNum);
        TThread2 t2 = new TThread2(pNum);
        t1.start();
        t2.start();
        
    }

}

class PPNums {
    public synchronized static void printNum() {
        for(int i = 0 ;i < 20;i++) {
            System.out.println("hello:"+i);
        }
    }
    public synchronized void printNum2() {
        for(int i = 0 ;i < 20;i++) {
            System.out.println("hahahhahah:"+i);
        }
    }
}
class TThread extends Thread{
    PPNums pNum;
    
    public TThread(PPNums pNum) {
        super();
        this.pNum = pNum;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        pNum.printNum();
    }
    
}
class TThread2 extends Thread{
    PPNums pNum;
    
    public TThread2(PPNums pNum) {
        super();
        this.pNum = pNum;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        pNum.printNum2();
    }
    
}

输出

hello:0
hahahhahah:0
hahahhahah:1
hahahhahah:2
hahahhahah:3
hahahhahah:4
hahahhahah:5
hahahhahah:6
hello:1
hello:2
hahahhahah:7
hello:3
hahahhahah:8
hello:4
hahahhahah:9
hello:5
hello:6
hello:7
hello:8
hello:9
hello:10
hello:11
hello:12
hello:13
hello:14
hello:15
hello:16
hello:17
hello:18
hello:19
hahahhahah:10
hahahhahah:11
hahahhahah:12
hahahhahah:13
hahahhahah:14
hahahhahah:15
hahahhahah:16
hahahhahah:17
hahahhahah:18
hahahhahah:19
上一篇 下一篇

猜你喜欢

热点阅读