我想暂停一个正在运行的线程,转去执行另一个方法,执行完后,恢复线程,即让线程继续执行,请问该怎么做啊

解决方案 »

  1.   

    我这边有例子。
    就是两个线程的执行互相切替的。
    给你看下。实现的东西就是 两个线程对同一个数进行运算。
    一个线程只对这个数 加1,
    另外一个线程对这个数 减1.
    这个数初始值 是 0.
    打印的结果是 只能输出0或者1,不允许其他的值。所以就要对这两个线程 进行控制了。
    加过之后,就要减,然后再加,来回切替。
    /**
     * @author bzwm
     *
     */
    public class ThreadTest {
    public static void main(String args[]){
    final Simple s = new Simple();

    Thread t1 = new Thread(new Runnable(){
    public void run() {
    try {
    for (int i = 0; i < 10; i++)
    s.increase();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });

    Thread t2 = new Thread(new Runnable(){
    public void run() {
    try {
    for (int i = 0; i < 10; i++)
    s.decrease();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });

    t1.start();
    t2.start();
    }
    }class Simple{
    private int count = 0;

    public synchronized void increase() throws InterruptedException{
    if(count > 0){
    wait();
    }
    Thread.sleep(1000);
    count++;
    print();
    notify();
    }

    public synchronized void decrease() throws InterruptedException{
    if(count < 1){
    wait();
    }
    Thread.sleep(1000);
    count--;
    print();
    notify();
    }

    private void print(){
    System.out.println(count);
    }
    }
      

  2.   

    Process finished with exit code 0 /** 
    * 计算输出其他线程锁计算的数据 

    * @author leizhimin 2008-9-15 13:20:38 
    */ 
    public class ThreadA { 
        public static void main(String[] args) { 
            ThreadB b = new ThreadB(); 
            //启动计算线程 
            b.start(); 
            //线程A拥有b对象上的锁。线程为了调用wait()或notify()方法,该线程必须是那个对象锁的拥有者 
            synchronized (b) { 
                try { 
                    System.out.println("等待对象b完成计算"); 
                    //当前线程A等待 
                    b.wait(); 
                } catch (InterruptedException e) { 
                    e.printStackTrace(); 
                } 
                System.out.println("b对象计算的总和是:" + b.total); 
            } 
        } 
    }
     
    /** 
    * 计算1+2+3 ... +100的和 

    * @author leizhimin 2008-9-15 13:20:49 
    */ 
    public class ThreadB extends Thread { 
        int total;     public void run() { 
            synchronized (this) { 
                for (int i = 0; i < 101; i++) { 
                    total += i; 
                } 
                //(完成计算了)唤醒在此对象监视器上等待的单个线程,在本例中线程A被唤醒 
                notify(); 
            } 
        } 
    }
     
    等待对象b完成计算 
    b对象计算的总和是:5050