主方法:
package com.duoxiancheng;
public class SellTicketsMain {
public SellTicketsMain() {}
public static void main(String[] args){
//调用Runnable实现
// SellTicketsThread sellTicketsThread = new SellTicketsThread();
// Thread w1 = new Thread(sellTicketsThread,"窗口1");
// Thread w2 = new Thread(sellTicketsThread,"窗口2");
// Thread w3 = new Thread(sellTicketsThread,"窗口3");
// Thread w4 = new Thread(sellTicketsThread,"窗口4");
// Thread w5 = new Thread(sellTicketsThread,"窗口5");
//继承Thread实现
SellTicketsThread2 w1 = new SellTicketsThread2("窗口1");
SellTicketsThread2 w2 = new SellTicketsThread2("窗口2");
SellTicketsThread2 w3 = new SellTicketsThread2("窗口3");
SellTicketsThread2 w4 = new SellTicketsThread2("窗口4");
SellTicketsThread2 w5 = new SellTicketsThread2("窗口5");
w1.start();
w2.start();
w3.start();
w4.start();
w5.start();
}
}
方法一:实现Runnable接口
package com.duoxiancheng;
public class SellTicketsThread implements Runnable{
private int ticketCount = 50;
static Object lock = "aa";
public SellTicketsThread(){}
@Override
public void run() {
while (ticketCount>0){
synchronized (lock){
if(ticketCount > 0){
System.out.println(Thread.currentThread().getName()+"正在卖第:"+ticketCount+"张票"+",还剩"+(ticketCount-1)+"张票");
ticketCount--;
if (ticketCount == 0){
System.out.println("票已卖完");
}
}else {
System.out.println("票已卖完");
}
}
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
方法二:继承Thread
package com.duoxiancheng;
public class SellTicketsThread2 extends Thread {
public SellTicketsThread2(String name){
super(name);
}
static int ticketCount = 50;
static Object lock = "aa";
@Override
public void run() {
while(ticketCount > 0){
synchronized (lock){
if (ticketCount > 0){
System.out.println(Thread.currentThread().getName()+"正在卖第:"+ticketCount+"张票"+",还剩"+(ticketCount-1)+"张票");
ticketCount--;
if (ticketCount == 0){
System.out.println("票已卖完");
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}