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 :(得分: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();
}
}
答案 1 :(得分: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
}