class TextThread implements Runnable{
private int num = 5;
@Override
public void run() {
while(true){
// 同步代碼塊
synchronized (this) {
if(num > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "出錯了!");
}
System.out.println(Thread.currentThread().getName() + "數字爲:" + num--);
}else{
System.out.println(Thread.currentThread().getName() + "退出來!!!");
break;
}
}
}
}
}
public class SynchronizedTest {
public static void main(String[] args) {
TextThread t = new TextThread();
// 啓動2個線程,
new Thread(t).start();
new Thread(t).start();
}
}
【多線程】synchronized同步塊
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.