解决方案 »

  1.   

    呃ThreadB先执行了,所以你应该把wait和notify换个位置 public class ThreadManage { public static void main(String[] args) {
    ThreadB b = new ThreadB();
    b.start(); System.out.println("线程b启动");
    synchronized (b) {
    try {
    System.out.println("等待线程b完成");
    b.notify();
    b.join();
    System.out.println("现在回到主函数线程");
    } catch (Exception e) {
    }
    }
    System.out.println("连加的结果是:" + b.total);
    }}class ThreadB extends Thread {
    int total; public void run() {
    synchronized (this) {
    try {
    wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("线程B启动");
    for (int i = 0; i < 50; i++) {
    total += i;
    System.out.print("total is " + total + " ");
    }
    }
    }
    }
      

  2.   


    public class ThreadManage { /**
     * No-arg constructor
     */
    public ThreadManage() {
    } public static void main(String[] args) {
    CalculateTask taskB = new CalculateTask(50);
    Thread b = new Thread(taskB);
    System.out.println("Thread B is running");
    System.out.println("Wait thread B complete");
    b.start();
    try {
    b.join();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("B Result is " + taskB.getTotal());
    }
    }class CalculateTask implements Runnable {
    int total;
    int addTimes; /**
     * TODO
     * 
     * @param addTimes
     */
    public CalculateTask(int addTimes) {
    this.addTimes = addTimes;
    } public int getTotal() {
    return total;
    } public void run() {
    synchronized (this) {
    for (int i = 1; i <= addTimes; i++) {
    total += i;
    System.out.println("total is " + total + " ");
    }
    }
    System.out.println("Now return main function...");
    }
    }
      

  3.   


    package com.liandy.test; public class Test { public static void main(String[] args) throws InterruptedException {
    ThreadB b = new ThreadB();
    b.start();
    Thread.sleep(10);
    System.out.println("等待线程b完成");
    synchronized (b) {
    try {
    b.notify();
    System.out.println("现在回到主函数线程");
    } catch (Exception e) {
    }
    }
    System.out.println("连加的结果是:" + b.total);
    }}class ThreadB extends Thread {
    int total; public void run() {
    synchronized (this) {
    System.out.println("线程B启动");
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    for (int i = 0; i < 50; i++) {
    total += i;
    System.out.print("total is " + total + " ");
    }
    System.out.println();
    }
    }
    }