一个类可以在Java中为两个不同的线程有两个run方法吗?

时间:2014-04-18 20:37:13

标签: java multithreading

    public void run(){
try{for(int i=5;i>0;i--){
      System.out.println("My Thread: " +i);
      t.sleep(2000);
   }//end of for
}catch(InterruptedException e){System.out.println("MyThread Interrupted");}
  System.out.println("MyThread exiting"); }
}//end of class

就像我想要两个线程一样,唯一的区别是t.sleep(1000)和t1.sleep(2000)。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

该类应该为sleepTime添加一个额外的构造函数。

public class MyRunnable implements Runnable() {
    private final long sleepTime;

    public MyRunnable(long sleepTime) {
        this.sleepTime = sleepTime;
    }

    @Override public void run() {
        // ...
        Thread.sleep(sleepTime);
    }