java中的线程同步问题 模拟出售火车票


/*
 功能:模拟火车售票窗口
 Thread.currentThread().getName()//获取到当前线程的名称
 1.解决所有线程共享 tickets。
 解决思路:①将tickets的数据类型改为static。创建了3个窗口, 每一个窗口代表一个线程。
                    ② 创建一个主窗口对象,创建三个线程对象,分别表示3个线程,传入相同的参数(窗口对象)。
 2.解决同一张票被卖出去多次。(程序的并发执行造成的,多个线程同时访问tickets)
 解决思路:(保证其原子性)当a线程在执行某段代码的时候,其他线程必须等待a执行完之后才能执行这段代码。
                      在需要同步的代码段上加入synchronized (this){}//对象锁 将要同步的代码块包起来
 */
//售票主窗口
class TicketWindows implements Runnable {
private int tickets = 2000;// 总票数


public void run() {
while (true) {
//if else 要保证其原子行 同步代码块
synchronized (this) {
if (tickets > 0) {
// 显示售票信息
System.out.println(Thread.currentThread().getName()
+ "正在售票中   ....还剩" + tickets + "张票");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickets--;
} else {
// 退出售票窗口
break;
}
}
// 判断是否还有票
}
}
}


public class TestTickets {


public static void main(String[] args) {
/*

 ///创建了3个窗口 每一个窗口代表一个线程

                      TicketWindows tWindows1=new TicketWindows();

      TicketWindows tWindows2=new TicketWindows(); 

                      TicketWindows tWindows3=new TicketWindows(); 

                      Thread thread1=new Thread(tWindows1);

     Thread thread2=new Thread(tWindows2);

                     Thread thread3=newThread(tWindows3);

                     thread1.start(); 

                     thread2.start();

                     thread3.start();

*/
TicketWindows tWindows1 = new TicketWindows();
Thread thread1 = new Thread(tWindows1);
Thread thread2 = new Thread(tWindows1);
Thread thread3 = new Thread(tWindows1);
thread1.start();
thread2.start();
thread3.start();


}


}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值