创建三个窗口同时卖票,总票数为100
方式一:使用继承Thread类的方式
class Window extends Thread{
private static int ticket = 100;
@Override
public void run() {
while (true){
if(ticket > 0){
System.out.println(getName() + ":卖票,票号为:" + ticket);
ticket--;
}else{
break;
}
}
}
}
public class WindowTest {
public static void main(String[] args) {
Window t1 = new Window();
Window t2 = new Window();
Window t3 = new Window();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
方式二:使用实现Runnable接口的方式
class Window1 implements Runnable{
private int ticket = 100;
@Override
public void run() {
while(true){
if (ticket > 0){
System.out.println("售票窗口为:" + Thread.currentThread().getName() + ", 票号为:" + ticket);
ticket--;
}else{
break;
}
}
}
}
public class WindowTest1 {
public static void main(String[] args) {
Window1 window1 = new Window1();
Thread t1 = new Thread(window1);
Thread t2 = new Thread(window1);
Thread t3 = new Thread(window1);
t1.setName("窗口1");
t1.start();
t2.setName("窗口2");
t2.start();
t3.setName("窗口3");
t3.start();
}
}