兩個執行緒輸出12121212
阿新 • • 發佈:2020-12-29
public class PrintNumber extends Thread{
private int mNumber ;
private volatile boolean switchThread = true;
private Object lock;
public PrintNumber(int number,Object lock){
mNumber = number;
this.lock = lock;
}
@Override
public void run() {
while (switchThread) {
synchronized (lock) {
System.out.print(mNumber);
try {
sleep(10);
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e. printStackTrace();
}
}
}
}
public void stop2(){
switchThread = false;
}
public static void main(String[] args){
Object lock = new Object();
PrintNumber thread1 = new PrintNumber(1,lock);
PrintNumber thread2 = new PrintNumber (2,lock);
thread1.start();
thread2.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.stop2();
thread2.stop2();
synchronized (lock){
lock.notifyAll();
}
}
}
輸出結果:
這個沒有實在意義,就是看到一個面試題的一個練手,沒想到中間還是出現了問題,不過很快就解決了,只是個記錄。