Java多线程模拟电影售票过程
用多线程模拟电影售票过程(Java实训),供大家参考,具体内容如下
实训目的:
多线程的实现、线程同步
实训要求:
总票数和售票窗口数由键盘输入,用每个线程处理一个窗口的售票。
Test.java
package program5;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int ticks,windows;
System.out.println("请输入总票数:");
ticks=sc.nextInt();
System.out.println("请输入售票窗口数:");
windows=sc.nextInt();
tickets lockThread=new tickets();
lockThread.setTickets(ticks);
for(int i=1;i<=windows;i++)
new Thread(lockThread,"窗口"+i).start();
}
}
tickes.java
package program5;
import java.util.concurrent.locks.*;
public class tickets implements Runnable {
private int tickets;
public int getTickets() {
return tickets;
}
public void setTickets(int tickets) {
this.tickets = tickets;
}
private final Lock lock=new ReentrantLock();
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
lock.lock();
if(tickets>0) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()
+"正在发售第"+tickets--+"张票");
}catch(InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
else {
System.exit(0);
}
}
}
}
结果显示:
以上是 Java多线程模拟电影售票过程 的全部内容, 来源链接: utcz.com/z/344209.html