现实中也存在这样的情况: 模拟一个火车站的售票系统,假如当日从A地发往B地的火车票只有10张,且允许所有窗口卖这10张票,每一个窗口也相当于一个线程。
1、Runnable接口实现
代码语言:javascript复制public class Main {
public static void main(String[] args) {
Test m = new Test();
Thread w1 = new Thread(m, "window 1");
Thread w2 = new Thread(m, "window 2");
Thread w3 = new Thread(m, "window 3");
w1.start();
w2.start();
w3.start();
}
}
class Test implements Runnable {
private int n = 10;
public void run() {
while (n > 0) {
System.out.println(n-- " is saled by " Thread.currentThread().getName());
}
}
}
2、Thread子类实现
代码语言:javascript复制public class Main {
public static void main(String[] args) {
Ticket t = new Ticket();
Test w1 = new Test(t,"window 1");
Test w2 = new Test(t,"window 2");
Test w3 = new Test(t,"window 3");
w1.start();
w2.start();
w3.start();
}
}
class Ticket {
int tic = 10;
}
class Test extends Thread{
private Ticket tick;
public Test(Ticket tick, String name){
super(name);
this.tick = tick;
}
public void run(){
while(tick.tic > 0){
System.out.println(tick.tic -- " is saled by " Thread.currentThread().getName());
}
}
}