实验报告七
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
代码:
package hello.java;
public class Ticket implements Runnable {
private int ticket=1000;
public int getTicket() {
return ticket;
}
public void setTicket(int ticket) {
this.ticket = ticket;
}
public void run()
{
for(int i=0;i<1000;i++)
{
synchronized(this)
{
if(ticket>0) {
try {
Thread.sleep(1000);
}catch(InterruptedException ie)
{
ie.printStackTrace();
}
finally { System.out.println(Thread.currentThread().getName() + "卖票:ticket" +ticket-- );
}
}
}
}
}
}
package hello.java;
public class Demo06 {
public static void main(String args[])
{
Ticket my = new Ticket();
Thread t1=new Thread(my,"窗口一");
Thread t2=new Thread(my,"窗口二");
Thread t3=new Thread(my,"窗口三");
Thread t4=new Thread(my,"窗口四");
Thread t5=new Thread(my,"窗口五");
Thread t6=new Thread(my,"窗口六");
Thread t7=new Thread(my,"窗口七");
Thread t8=new Thread(my,"窗口八");
Thread t9=new Thread(my,"窗口九");
Thread t10=new Thread(my,"窗口十");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
心得:这题我照着书上P251页打的,自我感觉还行,不是很难,内心分分钟就接受了这个代码。
第九周课程总结
多线程:实现多线程代码有两种方式一种是继承Thread类;一种是实现runable接口
继承Thread类
class 类名称 extends Thread{
属性……;
方法……;
}
public void run()
{
线程主体;
}
}
用继承Thread类实现多线程时要注意正确地启动线程,是不能直接调用run()方法的,而是应该调用从Thread类中继承而来的start()方法
实现Runnable接口
class 类名称 implements Runnable{
属性……
方法……
public void run(){
线程主体;
}
}