A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张林敏 中级黑马   /  2013-5-4 21:57  /  1587 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张林敏 于 2013-5-4 22:31 编辑

  1. <P>
  2. public class ThreadMain {
  3. /**
  4.   * @param args
  5.   * @throws InterruptedException
  6.   */
  7. public static void main(String[] args) throws InterruptedException {
  8.   StringBuffer sb = new StringBuffer("Start:");
  9.   Thread thread1 = new Thread1(sb);
  10.   Thread thread2 = new Thread2(sb);
  11.   thread1.start();
  12.   thread2.start();
  13.   System.out.println(sb);
  14. }
  15. }
  16. class Thread1 extends Thread {
  17. private StringBuffer sb;
  18. public Thread1(StringBuffer sb) {
  19.   super();
  20.   this.sb = sb;
  21. }
  22. @Override
  23. public void run() {
  24.   sb.append("\n[Thread1]");
  25.   for (int i = 0; i < 100; i++) {
  26.    sb.append(" "+i+" ");
  27.   }
  28. }
  29. }
  30. class Thread2 extends Thread {
  31. private StringBuffer sb;
  32. public Thread2(StringBuffer sb) {
  33.   super();
  34.   this.sb = sb;
  35. }
  36. @Override
  37. public void run() {
  38.   sb.append("\n[Thread2] Hello 黑马训练营 !");
  39. }
  40. }</P>
复制代码
像在上述的代码 要怎样才能先运行完 线程 thread1 与线程thread2 后在调用打印输出 ?



评分

参与人数 1技术分 +1 收起 理由
曹睿翔 + 1 赞一个!

查看全部评分

3 个回复

倒序浏览
join:
当A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。

  StringBuffer sb = new StringBuffer("Start:");
  Thread thread1 = new Thread1(sb);
Thread thread2 = new Thread2(sb);
  thread1.start();
thread1.join();
  thread2.start();
thread2.join();
  System.out.println(sb);
主线程按顺序执行代码,当执行到thread1.start();时,线程1开启,这时线程1和主线程随机被分配CPU使用权,当主线程获得使用权时会继续按顺序执行下面的代码。
当执行到 thread1.join();时,主线程会等待,直到线程1执行完才又恢复到执行状态,继续往下执行。线程2同样如此。故只有先运行完 线程 thread1 与线程thread2 后再调用打印输出
回复 使用道具 举报
yp324 发表于 2013-5-4 22:25
join:
当A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。

嗯,非常感谢....
回复 使用道具 举报
如果问题解决请再次编辑,修改为已解决,若还有疑问,请继续追问
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马