三种实现方式
继承Thread类,synchronized同步代码块
public class SellTicket extends Thread {
// 多个对象共享,必须static修饰
private static int tickets = 100;
@Override
public void run() {
while (true) {
synchronized (SellTicket.class) {
try {
sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
if (tickets > 0) {
System.out.println(getName() + " 正在出售第 " + tickets-- + " 张票");
}
}
}
}
}
public class TicketDemo {
public static void main(String[] args){
SellTicket thread01 = new SellTicket();
SellTicket thread02 = new SellTicket();
SellTicket thread03 = new SellTicket();
thread01.setName("窗口一");
thread02.setName("窗口二");
thread03.setName("窗口三");
thread01.start();
thread02.start();
thread03.start();
}
}
实现runnable接口,同步代码块
public class SellTicket2 implements Runnable {
// 多个对象共享,必须static修饰
private static int tickets = 100;
@Override
public void run() {
while (true) {
synchronized (SellTicket2.class) {
if (tickets > 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 正在出售第 " + tickets-- + " 张票");
}
}
}
}
}
public class TicketDemo2 {
public static void main(String[] args) {
SellTicket2 sellTicket2 = new SellTicket2();
Thread thread01 = new Thread(sellTicket2);
Thread thread02 = new Thread(sellTicket2);
Thread thread03 = new Thread(sellTicket2);
thread01.setName("窗口一");
thread02.setName("窗口二");
thread03.setName("窗口三");
thread01.start();
thread02.start();
thread03.start();
}
}
实现runable接口,Lock锁实现线程安全
public class SellTicket3 implements Runnable {
// 多个对象共享,必须static修饰
private static int tickets = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();
if (tickets > 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 正在出售第 " + tickets-- + " 张票");
}
lock.unlock();
}
}
}
public class TicketDemo3 {
public static void main(String[] args) {
SellTicket3 sellTicket3 = new SellTicket3();
Thread thread01 = new Thread(sellTicket3);
Thread thread02 = new Thread(sellTicket3);
Thread thread03 = new Thread(sellTicket3);
thread01.setName("窗口一");
thread02.setName("窗口二");
thread03.setName("窗口三");
thread01.start();
thread02.start();
thread03.start();
}
}