java 多线程 四个窗口卖100张票 


public class IOTest {
    public static void main(String[] args) {
        TicketSell t1 = new TicketSell();
        TicketSell t2 = new TicketSell();
        TicketSell t3 = new TicketSell();
        TicketSell t4 = new TicketSell();

        t1.setName("第一号窗口");
        t2.setName("第二号窗口");
        t3.setName("第三号窗口");
        t4.setName("第四号窗口");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
class TicketSell extends Thread{

    private static int ticket = 100;

    @Override
    public void run() {
        //在循环开始外围进行同步代码块,当第一个线程进入的时候,因为一直在循环所以代码没有执行完
        //其他的线程不能执行该同步代码块的代码
        while(ticket>0) {
            synchronized (TicketSell.class) {
                if(ticket>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(this.getName()+"卖出第 "+ticket +"号票");
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}

4个线程一起卖 1000张票,每卖出100张。票价涨100,原价500.最后打印每个线程卖出的票和总钱数

/**
 * @Auther: liuhaidong
 * Data: 2020/3/2 0002、18:12
 * Description:
 * @version: 1.0
 */
public class IOTest {
    public static void main(String[] args) {
        TicketSell t1 = new TicketSell();
        TicketSell t2 = new TicketSell();
        TicketSell t3 = new TicketSell();
        TicketSell t4 = new TicketSell();

        t1.setName("第一号窗口");
        t2.setName("第二号窗口");
        t3.setName("第三号窗口");
        t4.setName("第四号窗口");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class TicketSell extends Thread{

    private static int ticket = 1000;
    private static int index =0;
    private static int money = 500;
    @Override
    public void run() {
        //在循环开始外围进行同步代码块,当第一个线程进入的时候,因为一直在循环所以代码没有执行完
        //其他的线程不能执行该同步代码块的代码
        while(ticket>0) {
            synchronized (TicketSell.class) {
                if(ticket>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    money = (int) (Math.floor(index/100)*100)+500;
                    System.out.println(this.getName()+"卖出第 "+ticket +"号票"+money+"票钱");
                    ++index;
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}