模拟火车票售票(多线程)

★多窗口卖票
多线程互斥共享“基本数据类型数据”资源
已知:有200张票,4个窗口
思路:每个窗口用一个线程来模拟,共享200张票
方法一:共享一个对象,则拿到的变量即被共享。

public class TicketRunnable implements Runnable {
    private int sum=200;//sum是基本数据类型,不能用作对象锁,所以要给sum配一把对象锁
//  private Object obj=new Object();//obj--新建一个与sum共享变量的平行的对象
    private String name;
    public TicketRunnable(String name){
        this.name=name;
    }
    @Override
    public void run() {
        while(true){
            synchronized (this) {//用一个和sum平行的对象也可以,但必须是对象(Object obj=new Object();)
                if (sum > 0) {
                    System.out.println(name + ":" + sum);
                    sum--;
                }else{
                    break;
                }
            }
        }
    }
//总结:非静态变量要作对象锁时,直接用this代替
}
public class client {
    public static void main(String[] args) {
        TicketRunnable ticket=new TicketRunnable("窗口1");
        Thread t1=new Thread(ticket);
        t1.start();
        Thread t2=new Thread(ticket);
        t2.start();
        Thread t3=new Thread(ticket);
        t3.start();
        Thread t4=new Thread(ticket);
        t4.start();
    }
}

方法二:用静态sum表示被共享的火车票。

public class TicketRunnable implements Runnable {
    private static int sum=200;//sum是基本数据类型,不能用作对象锁,所以要给sum配一把对象锁
    private static Object obj=new Object();//obj--新建一个与sum共享变量的平行的对象,代替sum作对象锁
    private String name;
    public TicketRunnable(String name){
        this.name=name;
    }
    @Override
    public void run() {
        while(true){
            synchronized (obj) {//拿锁,,
                if (sum > 0) {
                    System.out.println(name + ":" + sum);
                    sum--;
                }else{
                    break;
                }
            }//解锁
        }
    }
}
public class client {
    public static void main(String[] args) {
        Thread t1=new Thread(new TicketRunnable("窗口1"));
        t1.start();
        Thread t2=new Thread(new TicketRunnable("窗口2"));
        t2.start();
        Thread t3=new Thread(new TicketRunnable("窗口3"));
        t3.start();
        Thread t4=new Thread(new TicketRunnable("窗口4"));
        t4.start();
    }
}

你可能感兴趣的:(java多线程)