設計一個多線程程序如下:設計一個火車售票模擬程序。假如火車站要有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() + "\t當前票號:" + 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張票\n",
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();
}
}