栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

方法一:使用继承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();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号