Java線程輸出ABCD
package xufeng.java;
public class Printer implements Runnable{
// 輸出字符
String printStr = null;
// 下一個輸出對象
Printer nextPrinter = null;
public Printer(String str)
{
printStr = str;
}
public void setNextPrinter(Printer nextPr)
{
nextPrinter = nextPr;
}
@Override
public void run() {
for (int i = 0; i < 10; i++)
{
synchronized (nextPrinter) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(printStr);
nextPrinter.notifyAll();
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package xufeng.java;
public class MainTest {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Printer a = new Printer("A");
Printer b = new Printer("B");
Printer c = new Printer("C");
Printer d = new Printer("D");
// 設置前後關系
a.setNextPrinter(b);
b.setNextPrinter(c);
c.setNextPrinter(d);
d.setNextPrinter(a);
// 啟動線程。相隔一秒以免初始輸出順序混亂
new Thread(a).start();
Thread.sleep(1000);
new Thread(b).start();
Thread.sleep(1000);
new Thread(c).start();
Thread.sleep(1000);
new Thread(d).start();
}
}