1,第一个线程,做一个100次的循环,当循环到50次时暂停当前线程,启动第二个线程。
2,第二个线程做一个50次的循环,当循环完成之后,让第一个线程继续执行,结束第二个线程。
3,第一个线程完成剩下的50次循环。这个段代码该怎么写?

解决方案 »

  1.   

    package loader;class T1 extends Thread {
    int torun = 100; boolean[] control; Thread other; public T1(Thread other, boolean[] control) {
    this.control = control;
    this.other = other;
    } public void run() {
    synchronized (control) {
    for (int i = 1; i <= torun && control[0]; i++) {
    System.out.println("Run One on " + i);
    try {
    sleep(500);
    } catch (InterruptedException e1) {
    e1.printStackTrace();
    }
    if (i == torun/2) {
    control[0] = false;
    other.start();
    try {
    control.wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    }
    }
    }class T2 extends Thread {
    int torun = 50; boolean[] control; public void run() {
    synchronized (control) {
    for (int i = 1; i <= torun; i++) {
    System.out.println("Run Two on " + i);
    try {
    sleep(500);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    control[0] = true;
    control.notifyAll();
    }

    } public T2(boolean[] control) {
    this.control = control;
    }
    }public class ThreadSolution { /**
     * @param args
     */
    public static void main(String[] args) {
    boolean[] control = new boolean[2];
    control[0] = true;
    control[1] = false;
    Thread t2 = new T2(control);
    Thread t1 = new T1(t2, control);
    t1.start();
    }}