Java教程

【Java】使用线程模拟卖票并解决安全问题

本文主要是介绍【Java】使用线程模拟卖票并解决安全问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SellTicket.java

package maipiao;

public class SellTicket implements Runnable {
    private static int tickets = 100;
    private Object obj = new Object();
    private int x = 0;

    @Override
    public void run() {

        while (true) {
            if (x % 2 == 0) {
                //        加锁操作
//                synchronized (obj) {
//                synchronized (this) {
//                静态方法
                synchronized (SellTicket.class) {
                    if (tickets > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                        tickets--;
                    }
                }
            } else {
                sellTicket();
            }
            x++;
        }
    }

    private static synchronized void sellTicket() {

        if (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
            tickets--;
        }
    }
}

SellTicketDemo.java

package maipiao;

public class SellTicketDemo {
    public static void main(String[] args) {
        SellTicket st=new SellTicket();

        Thread t1=new Thread(st,"窗口1");
        Thread t2=new Thread(st,"窗口2");
        Thread t3=new Thread(st,"窗口3");

//        启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

这篇关于【Java】使用线程模拟卖票并解决安全问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!