Java学习笔记——多线程(二)

//继承Thread实现线程,开启多个线程,验证是否共享同一资源(属性值)

public class Demo04_Thread extends Thread {
private int ticket = 5;


public void run() {
SimpleDateFormat sdf = new SimpleDateFormat();
for (int i = 0; i <= 20; i++) {
if (ticket > 0) {
System.out.println("时间:" + sdf.format(new Date()) + "name" + Thread.currentThread().getName()
+ "正在卖票..." + (this.ticket--));
}
}
}


public static void main(String[] args) {
Demo04_Thread tt = new Demo04_Thread();
tt.setName("窗口1");
tt.start();
new Demo04_Thread().start();
new Demo04_Thread().start();
}
}

//接口方式实现线程,开启多个线程,验证是否共享同一资源(属性值)

public class Demo05_Thread implements Runnable {
private int ticket = 5;


public void run() {
saleTicket();
}


// 卖票的方法
public void saleTicket() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSSS");
System.out.println("时间:" + sdf.format(new Date()));


for (int i = 10; i <= 20; i++) {
if (this.ticket > 0) {
System.out.println("时间:" + sdf.format(new Date()) + "name" + Thread.currentThread().getName()
+ "正在卖票..." + (this.ticket--));
}
}
}


public static void main(String[] args) {
Demo05_Thread myRunTicket = new Demo05_Thread();
Thread tt = new Thread(myRunTicket);
tt.setName("窗口1");


new Thread(myRunTicket, "窗口2").start();
new Thread(myRunTicket, "窗口3").start();


tt.start();
// 验证是否共享同一资源


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值