gpt4 book ai didi

JAVA动态线程

转载 作者:行者123 更新时间:2023-11-29 03:30:30 26 4
gpt4 key购买 nike

我是 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;
}

最佳答案

您正在静态初始化您的线程!这意味着它在加载类时创建一次。

您的代码完全按照编写的目的执行。

您必须修改您的 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();
}
}

更多提示:

  • 将线程初始化代码放在一个方法中。
  • 不使用匿名类,在TimeThread中编写run()方法,将this传给Thread build 者
  • 使用 getter 和 setter,它们被认为是好的做法
  • 了解有关 Java 编程的更多信息...从我在您的代码中看到的情况来看,您根本不应该接触线程。
  • 你的“竞选”文本实际上显示了一个随机数......它真的不应该。

关于JAVA动态线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com