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