package com.zuosy.learn;
import java.util.HashMap;
import java.util.Iterator;
public class App {
public static void main(String[] args) {
MaiPiao piao = new MaiPiao(150);
Thread[] threads = new Thread[3];
String[] threadName = {"DM", "HN", "OL"};
for (int index = 0; index < threads.length; ++index) {
threads[index] = new Thread(piao);
threads[index].setName(threadName[index]);
piao.AddRecord(threads[index].getName());
}
for(Thread thread : threads) {
thread.start();
}
System.out.println("Done");
}
}
class MaiPiao implements Runnable {
private Long ticket;
private HashMap<String, Integer> ticketRecord =
new HashMap<String, Integer>();
private String threadName;
public MaiPiao(long ticket) {
this.ticket = ticket;
}
public void AddRecord(String thread) {
ticketRecord.put(thread, 0);
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
Iterator<String> it = ticketRecord.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
buffer.append(key).append(" : ").append(ticketRecord.get(key)).append('\n');
}
return buffer.toString();
}
public void run() {
// System.out.println("run:" + this);
while (true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep((long) (Math.random() * 5));
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
threadName = Thread.currentThread().getName();
if (ticket > 0) {
System.out.println(threadName + " ticket = " + ticket--);
ticketRecord.replace(threadName, ticketRecord.get(threadName) + 1);
if (ticket <= 0)
break;
}
else {
System.out.println(Thread.currentThread().getName() + "break");
return;
}
}
}
System.err.println(this);
}
}
网友评论