本帖最后由 胡建伟 于 2013-11-13 00:15 编辑
今天复习多线程,做练习时候在网上找到一个三线程问题:有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC
看似很简单,可是做起来费了很大劲,最后逛论坛找到一种使用join()方法实现,但是还是没有完全理解,希望高手们能帮忙详细解释下,除了此方法是否还有其他方法可以实现?
package itheimabiji;
public class duoxiancheng {
public static void main(String[] args) {
Thread_E tc = new Thread_E();
Thread_E tb = new Thread_E();
Thread_A ta = new Thread_A();
ta.setThread(tb);
tb.setThread(tc);
tc.setThread(ta);
ta.setName("A");
tb.setName("B");
tc.setName("C");
ta.start();
tb.start();
tc.start();
}
}
class Thread_A extends Thread {
Thread t;
public void setThread(Thread t) {
this.t = t;
}
public void run() {
int i = 0;
while(i++ < 10) {
System.out.print(Thread.currentThread().getName());
t.interrupt();
try {
this.join();
} catch (InterruptedException e) {
}
}
}
}
class Thread_E extends Thread {
Thread t;
public void setThread(Thread t) {
this.t = t;
}
public void run() {
int i = 0;
while(i++ < 10) {
try {
this.join();
} catch (InterruptedException e) {
}
System.out.print(Thread.currentThread().getName());
t.interrupt();
}
}
}
|