在java中暂停/恢复多个线程

时间:2012-10-30 20:19:21

标签: java multithreading resume suspend

尝试编写将运行,暂停和恢复3个线程的程序。

这是编码:

class Connectthread implements Runnable
{
public void run()
{
    for(int j=0;j<90;j+=10)
    System.out.println("Connecting..." + j + " Secs");
}
}

class DLoadthread implements Runnable
{
public void run()
{
    for(int d=0;d<60;d+=10)
    System.out.println("Downloading..." + d + " Secs");
}
}
class Runthread implements Runnable
{
public void run()
{
    for(int r=0;r<120;r+=10)
    System.out.println("Running..." + r + " Secs");
}
}
class EHAunitThread
{
Connectthread ct=new Connectthread();
DLoadthread dt=new DLoadthread();
Runthread rt=new Runthread();

public void main(String arg[])
{
    //putting threads into ready state.
    System.out.print("Starting threads\n");
    ct.start();
    dt.start();
    rt.start();

    System.out.print("Sleeping 3 seconds\n");
    safeSleep(3000, "Threads first sleep time interrupted\n");
    System.out.print("Suspending threads\n");
    ct.suspend();
    dt.suspend();
    rt.suspend();

    System.out.print("Sleep 5 seconds\n");
    safeSleep(5000, "Threads second sleep time interrupted\n");
    System.out.print("Resume threads\n");
    ct.resume();
    dt.resume();
    rt.resume();

    try
    {
        ct.join();
        dt.join();
        rt.join();
    }
    catch (InterruptedException e)
    {
        System.out.print("Join interrupted");
    }

    System.out.print("Testcase Completed");
    System.exit(0);
}
}

当我尝试编译它时,它不断给我14条error:cannot find symbol条消息。

据我所知,就语法而言,编码看起来是正确的。我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

您的类是Runnables,您可以在它们上调用Thread方法。您需要将它们包装在Thread对象中:

Thread ct=new Thread (newConnectthread());

另请注意,Thread#suspend()已弃用。

答案 1 :(得分:1)

Runnable没有start方法。您需要使用Thread类来封装Runnable s:

Thread ct = new Thread(new Connectthread());
Thread dt = new Thread(new DLoadthread());
Thread rt = new Thread(new Runthread());

答案 2 :(得分:1)

暂停和恢复()不安全尝试此aprocach:

public class Pauser{

  private boolean isPaused=false;

  public synchronized void pause(){
     isPaused=true;
    }

  public synchronized void resume(){
    isPaused=false;
    notifyAll();
  }

  public synchronized void look(){
    while(isPaused){
        wait();
      }
   }

}

public class MyRunnable implements Runnable{

  Pauser pauser;

  public MyRunnable(Pauser pauser){
     this.pauser=pauser;
   }

  public void run(){
    while(true){
       pauser.look();
    }
  }

public class Caller{

  Pauser pauser=new Pauser();
  for(int i = 0; i<1000;i++)
    new Thread(new MyRunnable(pauser)).start();

//pause all threads
pauser.pause();

//resume all threads
pauser.resume();
}