两种线程创建方式,实现卖票案列

两种线程创建方式,实现卖票案列,第1张

两种线程创建方式,实现卖票案列

方法一:使用继承Thread类实现

public class ThreadDemo extends Thread{
    static Object obj = new Object();
    //总票数为10张
    static int sum = 10;


    @Override
    public void run() {
        while (true){

            synchronized (obj){
                if (sum>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "买了1张票" + ",还剩" + --sum + "张票");

                }else {
                    System.out.println(Thread.currentThread().getName() + "票已售完!");
                    break;
                }
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        ThreadDemo th1 = new ThreadDemo();
        th1.setName("一号窗口:");
        th1.start();
        ThreadDemo th2 = new ThreadDemo();
        th2.setName("二号窗口:");
        th2.start();
    }
}

方法二:实现Runnable接口

public class RunnableDemo implements Runnable{
    static int sum = 10;
    static Object obj = new Object();


    @Override
    public void run() {
        while(true){
            synchronized (this){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(sum>0){
                    System.out.println(Thread.currentThread().getName() + "购买了1张票,还剩" + --sum + "张票");

                }else {
                    System.out.println(Thread.currentThread().getName() + "票已售完!");
                    break;
                }
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        RunnableDemo runnableDemo = new RunnableDemo();
        Thread th1 = new Thread(runnableDemo);
        Thread th2 = new Thread(runnableDemo);
        th1.setName("窗口一:");
        th2.setName("窗口二:");
        th1.start();
        th2.start();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5684156.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存