2017-04-20 82 views
0
Thread thread1; 
thread1 = new Thread() { 
    public void run() { 
     try { 
      Thread.sleep(1700); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     System.out.println("testing"); 
    } 
}; 
Thread thread2; 
thread2 = new Thread() { 
    public void run() { 
     try { 
      // ... your code here 
      Thread.sleep(1000); 
      System.out.println("testing"); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
}; 
thread1.start(); 
thread2.start(); 
System.out.println("testing"); 

这是我的程序的一个条纹化的版本,并突出了我需要在它睡觉的时间传递的问题,但环顾四周后我似乎无法得到它通过我只能找到有关传递给runnable的信息。我需要传递一个变量到一个线程

+0

*”我只能找到有关传递给runnable的信息。“*你为什么认为有区别? –

+0

“线程”可以与“Runnable”大致相同。然而,如果你想从字面上使用'Runnable',只需按照你的例子,然后使你的线程如下:'thread1 = new Thread(myRunnable)'。这实际上比子类化线程好(就像你有),因为它更灵活,也因为它使用聚合而不是继承(这是实现它的首选方法)。 – markspace

+0

我无法理解它/使它工作。我设法编辑和示例,并可以将它传递给runnable,但不能在运行时使用它,这意味着我不能在我的线程的主要部分中使用它,就像我想要的那样。 – Mrpandygardner

回答

0

尝试运行下面的类,你有任何问题

public class TestThread { 

    volatile static int time = 1700; 

    public static void main(String[] args) { 


     Thread thread1 = new Thread() { 
      @Override 
      public void run() { 
       try { 
        Thread.sleep(time); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       System.out.println("Thread1 Sleeped for : " + time + " millis"); 
      } 
     }; 
     thread1.start(); 

     Thread thread2 = new Thread() { 
      @Override 
      public void run() { 
       try { 
        Thread.sleep(time); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       System.out.println("Thread2 Sleeped for : " + time + " millis"); 
      } 
     }; 
     thread2.start(); 
    } 

} 
+0

无论如何,这可以修改为支持未知数量的线程和不同的时间为每个人 – Mrpandygardner

+0

正如你所看到的,时间不是最终的变量。所以可以根据需要多次修改它。你也可以在任何线程中使用这个变量 –

+0

但是可能被修改的值可能不会立即对每个线程可见(由于线程缓存)。所以您可能需要将此变量设置为volatile –

0

你可以尝试创建一个线程工厂,需要的睡眠时间和您的自定义代码来执行:

interface CodeExecutor { 
    void execute(); 
} 

static class ThreadFactory { 
    public static Thread newThread(int sleepTime, CodeExecutor customCode) { 
     return new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        customCode.execute(); 
        Thread.sleep(sleepTime); 
        System.out.println("testing"); 
       } catch (InterruptedException ex) { 
      Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     }); 
    } 
} 

public static void main(String[] args) { 
    Thread thread1 = ThreadFactory.newThread(100, new CodeExecutor() { 
     @Override 
     public void execute() { 
      // here goes your custom code 
     } 
    }); 

    thread1.start(); 
    // create other threads 
}