为了模拟真实环境,代码加入延时
- package com.kxg_09;
- public class SellTicekt implements Runnable {
- private int ticket = 100;
- @Override
- public void run() {
- while (true) {
- if (ticket > 0) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + "正在出售第"
- + (ticket--) + "张票");
- }
- }
- }
- }
复制代码- package com.kxg_09;
- /*
- * 实现Runnable接口
- */
- public class SellTicketDemo {
- public static void main(String[] args) {
- // 创建自定义类对象
- SellTicekt st = new SellTicekt();
- // 创建线程
- Thread t1 = new Thread(st);
- Thread t2 = new Thread(st);
- // 设置线程名称
- t1.setName("窗口1");
- t2.setName("窗口2");
- // 启动线程
- t1.start();
- t2.start();
- }
- }
复制代码 此时运行程序就会出现相同票卖多次和出现负数票的情况
|
|