设计一个多线程程序如下:设计一个火车售票模拟程序。假如火车站要有100张火车票要卖出,现在有5个售票点同时售票,用5个线程模拟这5个售票点的售票情况
1、要求打印出每个售票点所卖出的票号
2、各售票点不能售出相同票号的火车票
package com.hebust.java.third;
import java.util.Random;
public class SaleTicket implements Runnable {
public int total;
public int count;
public SaleTicket() {
total = 100;
count = 0;
}
public void run() {
while (total > 0) {
synchronized (this) {
if(total > 0) {
try {
//Thread.sleep(800);
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
total--;
System.out.println(Thread.currentThread().getName() + " 当前票号:" + count);
}
}
}
}
public static void main(String[] args) {
SaleTicket st = new SaleTicket();
for(int i=1; i<=5; i++) {
new Thread(st, "售票点" + i).start();
}
}
}
第二种方法
public class MyThread4 extends Thread
{
public static int tickets = 100; //static不能省
public static String str = new String("哈哈"); //static不能省
private Object obj = new Object();
public void run()
{
while (true)
{
synchronized (obj)
{
if (tickets > 0)
{
System.out.printf("%s线程正在卖出第%d张票
",
Thread.currentThread().getName(), tickets);
--tickets;
}
else
{
break;
}
}
}
}
}
public class rain
{
public static void main(String[] args)
{
MyThread4 aa1 = new MyThread4();
aa1.start();
MyThread4 aa2 = new MyThread4();
aa2.start();
}
}