我的程序需要2个类,它们以确定的间隔生成Threads
随机数。
HeltalsGenerator
定义Thread
,在决定的时间间隔内创建5个随机数,当创建HeltalsGenerator
类型的对象时,确定间隔。
SlumpTal1
创建并启动Threads
类型的HeltalsGenerator
。
SlumpTal2
创建并启动Threads
类型的4 HeltalsGenerator
数组。
package thread;
class HeltalsGenerator extends Thread {
private int x;
private int y;
public HeltalsGenerator(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
int m = (int) (Math.random() * (x + 1) - y);
System.out.println(m);
}
}
}
class SlumpTal1 {
Thread s1 = new Thread(new HeltalsGenerator(0, 9));
Thread s2 = new Thread(new HeltalsGenerator(-9, -1));
}
class SlumpTal2 {
Thread t1 = new Thread(new HeltalsGenerator(1, 4));
Thread t2 = new Thread(new HeltalsGenerator(5, 8));
Thread t3 = new Thread(new HeltalsGenerator(9, 12));
Thread t4 = new Thread(new HeltalsGenerator(13, 16));
Thread[] s = {t1, t2, t3, t4};
}
class Main {
public static void main(String[] args) {
SlumpTal1 T1 = new SlumpTal1();
T1.start();
SlumpTal2 T2 = new SlumpTal2();
T2.start();
}
}
T1.start();
和T2.start();
都会产生错误“无法找到符号:方法start()和SlumpTal1的变量T1”
答案 0 :(得分:1)
创建一个新类并执行它。
步骤:
Main.java
(优先于相同的包/文件夹)
public class Main {
public static void main(String[] args) {
// do your stuff, ask the user or what you want here, for example:
SlumpTal1 tail1 = new SlumpTal1(); // execute 2 threads
tail1.start();
SlumpTal2 tail2 = new SlumpTal2(); // execute 4 threads
tail2.start();
}
}
执行应用
来自command line。
javac Main.java // compile
java Main.java // execute
编辑HeltalsGenerator
public HeltalsGenerator(int x, int y) {
super(x + "-" + y);
this.x = x;
this.y = y;
}
注意:
imports