不多说了,上代码
import java.util.Vector;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2009</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class ThreadTest {
public ThreadTest() {
Vector<WorkingThread> vThread = new Vector<WorkingThread>();
for (int i = 0; i < 5; i++) {
WorkingThread getThe = new WorkingThread(i);
vThread.add(getThe);
getThe.start();
}
ManageThread manageThread = new ManageThread(vThread);
manageThread.start();
}
public synchronized void showResult(String str) {
System.out.println(str);
}
class ManageThread extends Thread {
int Tid = 0;
Vector<WorkingThread> vThread = new Vector<WorkingThread>();
public ManageThread(Vector<WorkingThread> _vThread) {
vThread = _vThread;
}
public void run() {
while (true) {
if (Tid == vThread.size()) {
Tid = 0;
}
for (int i = 0; i < vThread.size(); i++) {
if (i == Tid) {
synchronized (vThread.get(i)) {
vThread.get(i).notify();
}
}
}
Tid++;
try {
sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class WorkingThread extends Thread {
int str;
int id;
boolean running = true;
boolean isUsed = false;
public WorkingThread(int _str) {
str = _str * 1000;
id = _str;
}
public void run() {
while (running) {
try {
synchronized (this) {
wait();
}
showResult("thread:" + id + ":" + str);
str++;
} catch (InterruptedException ex) {
System.out.println("error");
}
try {
sleep(1000);
} catch (InterruptedException ex1) {
}
}
}
}
public static void main(String[] args) {
new ThreadTest();
}
}