package demo.thread;
class SaleTickeRunnableImopl implements Runnable {
/*static*/ int num = 50; //无需static关键字共享数据 //只有一个SaleTickeRunnableImopl对象
public static void main(String[] args) {
SaleTickeRunnableImopl s = new SaleTickeRunnableImopl();
Thread thread1 = new Thread(s, "1号窗口");
Thread thread2 = new Thread(s, "2号窗口");
Thread thread3 = new Thread(s, "3号窗口");
thread1.start();
thread2.start();
thread3.start();
}
@Override
public void run() {
//System.out.println("this:"+ this);//demo.RunnableImpl@7c344a45
//System.out.println("当前线程:"+ Thread.currentThread());//Thread[接口实现的线程,5,main]
while (true) {
synchronized ("锁") {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "卖出第" + num + "张票");
num--;
} else {
break;
}
}
}
}
}
多线程接口实现
最新推荐文章于 2024-09-02 20:59:26 发布
本文展示了一个使用Java多线程技术实现的售票系统案例。通过三个线程模拟不同的售票窗口,共同操作共享变量实现票务同步处理。该示例使用synchronized关键字确保线程安全。

3012

被折叠的 条评论
为什么被折叠?



