模拟卖火车票(Java创建线程)

/**
 * 
 */
package com.gds.ticket;

/**
 * @author 龚道松
 * @date 2019年4月22日上午8:12:38
 * @version 1.0
 */
// 模拟卖火车票
public class TicktetDemo {
	public static void main(String[] args) throws InterruptedException {
		TickteetThread t = new TickteetThread();
		Thread th = new Thread(t);
		th.setName("窗口1");
		th.start();
		Thread th2 = new Thread(t);
		th2.setName("窗口2");
		th2.start();
		Thread th3 = new Thread(t);
		th3.setName("窗口3");
		th3.start();
		Thread th4 = new Thread(t);
		th4.setName("窗口4");
		th4.start();
		Thread th5 = new Thread(t);
		th5.setName("窗口5");
		th5.start();
	}
}

 

/**
 * 
 */
package com.gds.ticket;

/**
 * @author 龚道松
 * @date 2019年4月21日下午8:51:40
 * @version 1.0
 */
//模拟卖火车票
public class TickteetThread implements Runnable {

	int ticktet = 100;
	Object obj = new Object();

	public void run() {
		while (true) {
			// 火车票大于0开始卖票
			synchronized (obj) {
				if (ticktet > 0) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ": " + ticktet--);
				} else {
					break;
				}
			}

		}
	}

}

Java创建线程

继承父类Thread
class MyThread extends Thread {
    public void run() {
        System.err.println("MyThread...");
    }
}
实现接口Runnable
class MyRunnable implements Runnable {
    public void run() {
        System.err.println("MyRunnable...");
    }
}
匿名内部类
Thread t = new Thread(new Runnable(){
    public void run() {
        System.out.println( "anonymous inner class..." );
    }
});
Lambda表达式(1.8)
Thread t = new Thread( () -> {
    System.out.println( "Lambda expression thread..." );
} );
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值