第一种:代码如下
package sell;
public class SellTicked extends Thread{
static int count=1000;//一千张票
static Object obj=new Object();
@Override
public void run() {
while(true){
try {
//线程睡眠两秒
Thread.sleep(2000);
//线程同步锁
synchronized(obj){
if(count>0){
//输出当前线程的name
System.out.println(this.getName()+"当前火车票号"+count--);
}else {
System.out.println("票卖完了");
//退出
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//main方法运行
public static void main(String[] args) {
SellTicked sc=new SellTicked();
sc.setName("第一窗口");
sc.start();
SellTicked sc1=new SellTicked();
sc1.setName("第二窗口");
sc1.start();
SellTicked sc2=new SellTicked();
sc2.setName("第三窗口");
sc2.start();
}
}
第二种
package sell;
public class SellTickedRunnable implements Runnable {
static int ticked = 1000;
static Object obj = new Object();
@Override
public void run() {
while(true){
try {
Thread.sleep(2000);
synchronized(obj){
if(ticked>0){
System.out.println(Thread.currentThread().getName()+“当前窗口火车票号”+ticked–);
}else{
System.out.println(“票卖完了”);
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SellTickedRunnable sr=new SellTickedRunnable();
Thread th=new Thread(sr);
th.setName("第一窗口");
th.start();
SellTickedRunnable sr2=new SellTickedRunnable();
Thread th2=new Thread(sr2);
th2.setName("第二窗口");
th2.start();
SellTickedRunnable sr3=new SellTickedRunnable();
Thread th3=new Thread(sr3);
th3.setName("第三窗口");
th3.start();
}
}