1

尝试编写将运行、挂起和恢复 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);
}
}

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

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

4

3 回答 3

2

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

Thread ct=new Thread (newConnectthread());

另请注意,不推荐使用Thread#suspend()

于 2012-10-30T20:23:25.097 回答
1

Runnable没有start办法。您需要使用Thread该类来封装Runnables:

Thread ct = new Thread(new Connectthread());
Thread dt = new Thread(new DLoadthread());
Thread rt = new Thread(new Runthread());
于 2012-10-30T20:23:58.903 回答
1

Suspend 和 resume() 是不安全的,试试这个:

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();
}
于 2013-02-27T20:43:55.023 回答