线程安全方式2Runnable---同步代码块

/**
* Runnable方式线程安全---同步代码块
*
* @Author: ITYW
* @Create 2020 - 10 - 26 - 18:47
*/
public class RunnableSecurity {
public static void main(String[] args) {
//创建一个对象即可
Runnable_Security runnable_security = new Runnable_Security();

Thread t1 = new Thread(runnable_security);
Thread t2 = new Thread(runnable_security);
Thread t3 = new Thread(runnable_security);

t1.setName("window1");
t2.setName("window2");
t3.setName("window3");

t1.start();
t2.start();
t3.start();

}
}
class Runnable_Security implements Runnable{
private static int ticket = 100;
@Override
public void run() {
while (true){
synchronized(this){
if (ticket > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖出了第"+ticket+"张");
ticket--;
}else {
break;
}
}
}
}
}
原文地址:https://www.cnblogs.com/ITYW/p/13880495.html