關(guān)鍵知識(shí)點(diǎn):synchronized、Runnable
synchronized:
1、使用同步代碼塊進(jìn)行賣票:
public class TicketsCodeBlock implements Runnable {
private int count = 100; //總票數(shù)目
public static void main(String[] args) {
TicketsCodeBlock tickets = new TicketsCodeBlock();
Thread t1 = new Thread(tickets);
Thread t2 = new Thread(tickets);
Thread t3 = new Thread(tickets);
t1.start();
t2.start();
t3.start();
}
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (this) { // 同步代碼塊
if (count > 0) {
try {
Thread.sleep(500); // 500ms
} catch (Exception e){
e.printStackTrace();
}
Thread t = Thread.currentThread();
System.out.println(t.getName() + " 剩余票的數(shù)目: " + (count--));
}
}
}
}
}
2、使用同步方法進(jìn)行賣票:
public class TicketsMethod implements Runnable {
private int count = 100; //總票數(shù)目
public static void main(String[] args) {
TicketsMethod tickets = new TicketsMethod();
Thread t1 = new Thread(tickets);
Thread t2 = new Thread(tickets);
Thread t3 = new Thread(tickets);
t1.start();
t2.start();
t3.start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sale();
}
}
// 使用同步方法進(jìn)行賣票
public synchronized void sale() {
if (count > 0) {
try {
Thread.sleep(500); // 500ms
} catch (Exception e){
e.printStackTrace();
}
Thread t = Thread.currentThread();
System.out.println(t.getName() + " 剩余票的數(shù)目: " + (count--));
}
}
}
}
}