多窗口卖票,需求如下: 假设一个影院有三个售票口,分别用于向儿童、成人和老人售票。 影院为每个窗口放有10张电影票,分别是儿童票、成人票和老人票。 三个窗口需要同时卖票, 而现在只有一个售票员,这个售票员就相当于一个CPU,三个窗口就相当于三个线程。
1 通过扩展Thread类来创建多线程
代码语言:javascript复制public class Main {
public static void main(String[] args) {
Test w1 = new Test("window 1");
Test w2 = new Test("window 2");
Test w3 = new Test("window 3");
w1.start(); // start 调用
w2.start();
w3.start();
}
}
class Test extends Thread{ // 继承 Thread
private int n = 10;
Test(String name){
super(name);
}
public void run(){ //重写
while(n > 0){
System.out.println(n -- " is saled by " currentThread().getName());
}
}
}
2、通过实现Runnable接口来创建 多线程 (推荐)
代码语言:javascript复制public class Main {
public static void main(String[] args) {
Test w1 = new Test("window 1");
Test w2 = new Test("window 2");
Test w3 = new Test("window 3");
Thread m1 = new Thread(w1);
Thread m2 = new Thread(w2);
Thread m3 = new Thread(w3);
m1.start();
m2.start();
m3.start();
}
}
class Test implements Runnable {
private int n = 10;
private String name;
Test(String name) {
this.name = name;
}
public void run() {
while (n > 0) {
System.out.println(n-- " is saled by " name);
}
}
}