java吧 关注:1,213,644贴子:12,657,981
  • 2回复贴,共1
//例10线程不同步的例子
class Printer1 {// 打印机类
void printMessage(String msg) {
System.out.println("开始打印信息:" + msg);
try {
Thread.sleep(1000);//休眠期间,其它线程将启动
} catch (InterruptedException e) {
System.out.println("中断");
}
System.out.println(msg+"结束打印\n");
}
}
class Client1 implements Runnable {// 线程类
String msg;
Printer1 pr;
Thread t;
public Client1(Printer1 pr1, String msg) {//构造器
pr = pr1;
this.msg = msg;
t = new Thread(this);
t.start();
}
public void run() {// 线程体
pr.printMessage(msg);
}
}
public class Synchronization1 {// 主类
public static void main(String args[]) {
Printer1 pr = new Printer1();
Printer1 pr1 = new Printer1();
Printer1 pr2 = new Printer1();
Printer1 pr3 = new Printer1();
System.out.println("用户准备打印: ");
// 创建四个线程,并启动
Client1 c1 = new Client1(pr, "I am user id : 101");
Client1 c2 = new Client1(pr1, "I am user id : 102");
Client1 c3 = new Client1(pr2, "I am user id : 103");
Client1 c4 = new Client1(pr3, "I am user id : 104");
try {
c1.t.join();
c2.t.join();
c3.t.join();
c4.t.join();
} catch (InterruptedException e) {
System.out.println("中断");
}
}
}

我想问下
c1.t.join();
c2.t.join();
c3.t.join();
c4.t.join();
有什么用??


1楼2015-12-22 13:40回复
    阻塞当前线程直到目标线程运行完毕


    IP属地:江苏来自Android客户端2楼2015-12-22 13:47
    收起回复