一、完成火车站售票程序的模拟。

要求:

(1)总票数1000张;

(2)10个窗口同时开始卖票;

(3)卖票过程延时1秒钟;

(4)不能出现一票多卖或卖出负数号票的情况。

代码:

public class Mythread extends Thread {
private int t=1000;
public int getT() {
return t;
}
public void setT(int t) {
this. = t;
}
public void run() {
for(int i = 0;i<5000;i++) { synchronized(this) {
if(t>0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票 = "+t--);
}
}
}
}
}
public class text {
public static void main(String[] args) {
Mythread m = new Mythread();
Thread m0 = new Thread(m,"窗口1") ;
Thread m1 = new Thread(m,"窗口2") ;
Thread m2 = new Thread(m,"窗口3") ;
Thread m3 = new Thread(m,"窗口4") ;
Thread m4 = new Thread(m,"窗口5") ;
Thread m5 = new Thread(m,"窗口6") ;
Thread m6 = new Thread(m,"窗口7") ;
Thread m7 = new Thread(m,"窗口8") ;
Thread m8 = new Thread(m,"窗口9") ;
Thread m9 = new Thread(m,"窗口10") ; m0.start();
m1.start();
m2.start();
m3.start();
m4.start();
m5.start();
m6.start();
m7.start();
m8.start();
m9.start(); }
}

结果

第七周实验报告&amp;课程总结-LMLPHP

学习总结

1、学习了线程等一系列相关的知识

2、认识了Thread类和实现Runnable接口以及它们两者之间的区别

3、取得和设置线程名称、判断线程是否启动、线程的强制转换、线程的休眠、中断、礼让。

4、同步与死锁固。

05-28 15:59