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同步块
最新推荐文章于 2023-02-19 07:15:13 发布