java多线程模拟售票
【摘要】 java多线程模拟售票
售票类:
package duoxiancheng;
import java.util.concurrent.TimeUnit;
/**
* @author yeqv
* @program A2
* @Classname Ticket
* @Date 2022/1/28 23:04
* @Email w16638771062@163.com
*/
public class Ticket implements Runnable {
//未设置票数,默认为100
private int num = 100;
public Ticket() {
}
//获取传入票数
public Ticket(int num) {
this.num = num;
}
public void run() {
while (true) {
//加锁,当一个进程进入时其他进程阻塞,防止数据出错
synchronized (this) {
try {
//延时1秒
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
if (num > 0) {
System.out.printf("[%s] 售出一张票,剩余%d张票%n", Thread.currentThread().getName(), --num);
} else {
System.out.printf("%n[%s] 票已售完,停止售票。", Thread.currentThread().getName());
break;
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
测试类:
package duoxiancheng;
/**
* @author yeqv
* @program A2
* @Classname Test4
* @Date 2022/1/28 23:03
* @Email w16638771062@163.com
*/
public class Test4 {
public static void main(String[] args) {
//传入票数
Ticket ticket = new Ticket(20);
//创建四个新线程并且更名
Thread thread = new Thread(ticket, "郑州站");
Thread thread1 = new Thread(ticket, "郑州东站");
Thread thread2 = new Thread(ticket, "郑州南站");
Thread thread3 = new Thread(ticket, "郑州北站");
//启动四个线程
thread.start();
thread1.start();
thread2.start();
thread3.start();
}
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)