Java多執行緒基礎—買票案例
這段程式碼是一個簡單的多執行緒同時買票的案例,建立三個執行緒買票,當票數賣完後另外一個執行緒負責將票數補回到100。
附上程式碼:
public class ThreadShare {
public static void main(String[] args) {
ShareDatas shareData = new ShareDatas();
new Thread(new ThreadRunnable1(shareData)).start();
new Thread(new ThreadRunnable2(shareData)).start();
new Thread(new ThreadRunnable2(shareData)).start();
new Thread(new ThreadRunnable2(shareData)).start();
}
}
class ThreadRunnable1 implements Runnable{
private ShareDatas shareData;
public ThreadRunnable1(ShareDatas shareData){
this.shareData = shareData;
}
@Override
public void run() {
while(true){
shareData.increatment();
}
}
}
class ThreadRunnable2 implements Runnable{
private ShareDatas shareData;
public ThreadRunnable2(ShareDatas shareData){
this.shareData = shareData;
}
@Override
public void run() {
while(true){
shareData.decreatment();
}
}
}
class ShareDatas{
private static int data;
public synchronized void increatment(){
System.out.println(“票已經售完請補充”);
while(data>0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
data = 100;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.notify();
}
public synchronized void decreatment(){
while(data<=0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
data–;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+”號視窗正在售票 “+”當前餘票是: “+data);
this.notify();
}
}
執行效果:
首先main方法建立四個執行緒,一個實現ThreadRunnable1,另外三個實現ThreadRunnable2。ThreadRunnable1和ThreadRunnable2都是共享一個ShareDatas類,並且都重寫了構造器(添加了共享引數data票數)和run()方法。在ShareDatas類中有票數data以及對data操作的兩個方法售票的decreatment()以及補票的increatment()。ThreadRunnable1的run()方法中呼叫的是increatment(),ThreadRunnable2呼叫了decreatment()。