线程安全方式02Runnable---同步方法

/**
* Runnable方式线程安全---同步方法
*
* @Author: ITYW
* @Create 2020 - 10 - 26 - 18:59
*/
public class RunnableSecurity02 {
public static void main(String[] args) {
Runnable_Security02 runnable_security02 = new Runnable_Security02();
Thread t1 = new Thread(runnable_security02);
Thread t2 = new Thread(runnable_security02);
Thread t3 = new Thread(runnable_security02);

t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");

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

class Runnable_Security02 implements Runnable{
private static int ticket = 100;
@Override
public void run() {
while (true){
sale();
}

}

private static synchronized void sale(){
if (ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ticket+"张");
ticket--;
}
}
}
posted @ 2020-10-26 19:42  ITYW  阅读(117)  评论(0编辑  收藏  举报