題目
1、用多線程程序設計方式模擬鐵路售票,一共100張,通過四個窗口賣完。分別用實現多線程程序設計的兩種方式完成。
效果
1.多線程方式效果
2.線程池方式效果
代碼
1.多線程方式
package P1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.lang.Thread.currentThread;
import static java.lang.Thread.sleep;
public class thread1 {
public static void main(String[] args){
Runnable window1=new Sold(100);
Runnable window2=new Sold(100);
Runnable window3=new Sold(100);
Runnable window4=new Sold(100);
Thread thread1=new Thread(window1);
Thread thread2=new Thread(window2);
Thread thread3=new Thread(window3);
Thread thread4=new Thread(window4);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class Sold implements Runnable{
private static Lock lock = new ReentrantLock();
private static Condition newSold=lock.newCondition();
private static int total;//火車票總數
public Sold(int total) {
this.total = total;
}
@Override
public void run() {
try {
rest();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void rest() {
lock.lock();
try {
while(total!=0){
Thread.sleep(5);
total-=1;
System.out.println("還剩"+total+"張票");
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
2.線程池方式效果
package P1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.lang.Thread.currentThread;
import static java.lang.Thread.sleep;
public class thread1 {
public static void main(String[] args){
//創建三個任務
ExecutorService executor= Executors.newFixedThreadPool(4);
executor.execute(new Sold(100));
executor.execute(new Sold(100));
executor.execute(new Sold(100));
executor.execute(new Sold(100));
executor.shutdown();
}
}
class Sold implements Runnable{
private static Lock lock = new ReentrantLock();
private static Condition newSold=lock.newCondition();
private static int total;//火車票總數
public Sold(int total) {
this.total = total;
}
@Override
public void run() {
try {
rest();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void rest() {
lock.lock();
try {
while(total!=0){
Thread.sleep(5);
total-=1;
System.out.println("還剩"+total+"張票");
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
思路
因爲多線程的並行是交替運行的,所以會導致結果出現的順序不一致,所以使用加鎖的方式迫使線程一定要等到當前線程結束後才能運行。