我是java的初学者,我有这个代码我做了,但是这个线程只执行一次,我怎么能让线程变得动态?
//主程序 - 创建2个线程,此时不幸的是只有1个正在运行
public static void main(String[] args){
timeThread ttm = new timeThread();
ttm.name = "map";
ttm.min = 1000;
ttm.max = 5000;
ttm.start();
timeThread tta = new timeThread();
tta.name = "arena";
tta.min = 6000;
tta.max = 10000;
tta.start();
}
//我正在调用程序的时间线程
static class timeThread{
static String name;
static int min;
static int max;
static int random;
static Thread t = new Thread () {
public void run () {
while (true){
random = genRandomInteger(min,max);
System.out.println("Thread named: "
+ name + " running for: "
+ random + " secconds...");
try {
Thread.sleep(random);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
};
void start(){
t.start();
}
}
//随机函数发生器
private static int genRandomInteger(int aStart, int aEnd){
int returnValue = aStart + (int)(Math.random()
* ((aEnd - aStart) + 1));
return returnValue;
}
答案 0 :(得分:4)
您正在静态初始化您的线程!这意味着它在加载类时创建一次。
您的代码完全按照其编写的方式执行。
您必须修改TimeThread
类:删除静态关键字并使变量成为类成员。像这样:
static class TimeThread implements Runnable {
String name;
int min;
int max;
int random;
Thread t;
public void run () {
while (true){
random = genRandomInteger(min,max);
System.out.println("Thread named: " + name + " running for: "
+ random + " secconds...");
try {
Thread.sleep(random);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
void start(){
t = new Thread (this);
t.start();
}
}
更多提示:
run()
中编写TimeThread
方法并将this
传递给Thread
构造函数