您的位置:首页 > 编程语言 > Java开发

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

2017-08-17 12:35 429 查看

//继承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();
// 验证是否共享同一资源

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: