线程分析-同步代码块-共享资源-卖票问题安全实例
package com.liujinghe.lianxi1.a_thread;
class SaleTicket2 implements Runnable{
//同步代码块,共享资源,加锁,线程安全
private static int ticket = 100;//总票数
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
//如果票数大于0 ,卖票
//对if语句加锁
synchronized("锁") {
if(ticket>0) {
//有票,开始卖票
System.out.println(Thread.currentThread().getName()+":卖出去第"+ticket+"张票");
ticket--;
//卖出去后,让线程休眠一段时间
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
//如果没票,退出循环
System.out.println("票卖完了");
break;
}
}
}
}
}
public class Demo2 {
public static void main(String[] args) {
//创建多个线程
Thread thread1 = new Thread(new SaleTicket2(),"天猫");
Thread thread2 = new Thread(new SaleTicket2(),"淘宝");
Thread thread3 = new Thread(new SaleTicket2(),"京东");
Thread thread4 = new Thread(new SaleTicket2(),"拼多多");
//开启线程
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
运行截图