/**
*
*/
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..." ); } ); |