1. 程式人生 > >多線程 售票 (同步)

多線程 售票 (同步)

tac ring true ren private lock method run object

public class Demo4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Tickets t=new Tickets();
        Thread th0=new Thread(t);
        Thread th1=new Thread(t);
        Thread th2=new Thread(t);
        th0.start();
        th1.start();
        th2.start();
    }

}
public class Tickets extends Thread{
    private int ticket=100;
    //對象鎖
    private Object obj=new Object();
    public void run(){
        while(true){
            synchronized (obj) {
                if(ticket>0){
                try {
                    Thread.sleep(10);
                } catch
(InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"出售第"+ticket--+"張票"); } } } } }

多線程 售票 (同步)