public class BuyTicket implements Runnable {
//票数
private static int nn=10;
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//来个锁
synchronized (this){
if(nn>0){
System.out.println(Thread.currentThread().getName()+"这是第"+(nn--)+"张票");
}
}
}
}
public static void main(String[] args) {
BuyTicket buyTicket= new BuyTicket();
Thread t1 = new Thread(buyTicket,"一号窗口:");
Thread t2 = new Thread(buyTicket,"二号窗口:");
Thread t3 = new Thread(buyTicket,"三号窗口:");
Thread t4 = new Thread(buyTicket,"四号窗口:");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
倒叙输出
public class Flashback implements Runnable {
@Override
public void run() {
for (int i = 0; i <=10 ; i++) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
}
public static void main(String[] args) {
Flashback flashback = new Flashback();
Thread thread= new Thread(flashback);
thread.start();
for (int i = 10; i >=1 ; i--) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
}
}