1.12306抢票 (线程 死锁)
方法一:
public class ThreadGetOneResource
{
private int ticket=1000;
public static void main(String[] args)
{
//多个线程抢占同一个资源
//所有的传值过程就是复制过程
//静态只能访问静态
ThreadGetOneResource one=new ThreadGetOneResource();
for(int i=0;i<3;i++)
{
new Thread(){ //匿名内部类(不能访问外部类)
public void run()
{
//加锁 某个线程 获得到锁 将它的代码全部都执行 执行完毕之后 才会释放锁
//1.必须是包装类型 2.全局只有一份
while(true)
{
synchronized (one)
{
if(one.ticket<=0)
{
break;
}
System.out.println(Thread.currentThread().getName()+"ticket的数量是="+one.ticket);
one.ticket--;
}
}
}
}.start();
}
}
}