线程实现多窗口卖票

Runnable的实现方式更适合来处理多个线程有共享数据的情况

继承Thread类

package Threads;

public class TicketThread extends Thread{
    static int number=10;
    static Object obj=new Object();
    @Override
    public void run() {
        while(true){
            synchronized(obj){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(number<=0){
                    break;
                }
                System.out.println(Thread.currentThread().getName()+":"+(number));
                number--;
            }
        }
    }
}
package Threads;

public class Ticketdemo {
    public static void main(String[] args) {
        TicketThread th1=new TicketThread();
        th1.setName("Thread窗口一");
        th1.start();
        TicketThread th2=new TicketThread();
        th2.setName("Thread窗口二");
        th2.start();
    }
}

实现Runnable接口

package Threads;

public class TicketThread2 implements Runnable {
    int number = 10;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (number <= 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + ":" + number);
                number--;
            }
        }
    }
}
package Threads;

public class Ticketdemo2 {
    public static void main(String[] args) {
        TicketThread2 t2=new TicketThread2();
        Thread th2=new Thread(t2);
        Thread th3=new Thread(t2);
        th2.setName("Runnable窗口一");
        th2.start();;
        th3.setName("Runnable窗口二");
        th3.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

outlier--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值