题目
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();
}
}
}
思路
因为多线程的并行是交替运行的,所以会导致结果出现的顺序不一致,所以使用加锁的方式迫使线程一定要等到当前线程结束后才能运行。