賣票執行緒問題解決(1)
未利用同步思想,會出現0,與-1的買票狀態
package ThreadDemo;
/*
* 售票系統的建立
* */
public class TicketDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1.建立售票物件
Ticket ticket = new Ticket();
//2.售票視窗的建立
Thread t1 = new Thread(ticket,"1視窗");
Thread t2 = new Thread(ticket,"2視窗");
Thread t3 = new Thread(ticket,"3視窗");
//3.視窗售票
t1.start();
t2.start();
t3.start();
}
}
-------------------------------Ticket執行緒介面,主要是implements Runnable--------------
package ThreadDemo;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
*多執行緒的售票,就相當於多個視窗售票
* */
public class Ticket implements Runnable{
//給定100張票
static int ticket = 100;
@Override
public void run() {
// TODO Auto-generated method stub
//模擬售票
while(true) {
if (ticket > 0) {
//模擬選座
try {
Thread.sleep(2);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在買票:" + ticket--);
}
}
}
}