public class TestTicket{
public static void main(String[] args){
SellTickets st = new SellTickets();
Thread t1 = new Thread(st,"窗口1--");
Thread t2 = new Thread(st,"窗口2--");
Thread t3 = new Thread(st,"窗口3--");
t1.start();
t2.start();
t3.start();
}
}
class SellTickets implements Runnable{
private int ticket=10;
private synchronized void SellTickets(){
try{
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +
"第 " + ticket + "张票已经售出。" );
ticket--;
this.wait();
this.notify();
}
catch(Exception e){
e.printStackTrace();
}
}
public synchronized void run(){
while(ticket>0){
SellTickets();
}
System.out.println(Thread.currentThread().getName() + "票已经售完,正在补票中,请等待。。。");
}
}
输出结果
我想要实现3个窗口轮流售票。怎么弄 实在搞不了了
建议你看看多线程的生成者和消费者
t1.start() ;
t2.start() ;
t3.start() ;
t1.join() ;
t2.join() ;
t3.join() ;
join() 等当前线程执行完 在执行其他线程
public class Maipiao implements Runnable{
int i =100000;
public static void main(String[] args) {
Maipiao m = new Maipiao();
Thread t1 = null;
for(int i=0;i<10;i++){
t1 = new Thread(m);
t1.start();
}
}
private synchronized void sale() {
if(i > 0){
System.out.println(Thread.currentThread() + "正在购买第" + i-- + "张票");
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
while (i>0) {
sale();
}
}
}