package ThreadWork.MyThread.Oldlianxi;
/**
* 模拟火车票的售票
* 分析
* 首先需要火车票的总数 卖出一张少一张
* 当火车票木有时 不再售票
* 使用多线程模拟售票
* 木有票时火车站还是开着的
*
*
* 问题:当多个线程共享一个数据时 有可能会发生错误
* 解决: 线程同步
* synchronized ():同步代码块和方法,被修饰的代码块和方法一旦被某个线程访问,则直接锁住,其他的线程无法访问
*
* A 同步代码块
* synchronized (锁对象){
*
* }
* 注意:锁对象需要被所有的线程共享
*
* B 同步方法 使用关键字synchronized 修饰的方法 一旦被一个线程访问
* 则整个方法被锁住无法访问
* synchronized
* 注意事项: 非静态方法的锁对象是this
* 静态方法的锁对象是当前类的字节码对象
* */
class Thick implements Runnable{
int thicknumber=100; //火车票总数
Object o=new Object();
@Override
public void run() {
while (true){
//售票
synchronized (o){
if (thicknumber>0){
//休息一下
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" : "+thicknumber--);
}
}
}
}
}
public class Demo3Thick {
public static void main(String[] args) {
Thick h1=new Thick();
// 创建线程实例
Thread t1=new Thread(h1);
t1.setName("窗口1");
Thread t2=new Thread(h1);
t2.setName("窗口2");
Thread t3=new Thread(h1);
t3.setName("窗口3");
//启动线程
t1.start();
// t1.wait();
t2.start();
t3.start();
}
}
线程同步(模拟火车站售票,以后可以学习的是锁优化)
最新推荐文章于 2022-02-10 19:21:12 发布
4263

被折叠的 条评论
为什么被折叠?



