我的程序需要2个类,这些类在确定的时间间隔内生成带有随机数的Threads
。HeltalsGenerator
定义一个Thread
,该HeltalsGenerator
在确定的间隔内创建5个随机数,该间隔将在创建SlumpTal1
类型的对象时确定。Threads
创建并启动2个HeltalsGenerator
类型的SlumpTal2
。Threads
创建并启动一个由HeltalsGenerator
类型的4个T1.start();
组成的数组。
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();
}
}
T2.start();
和都创建错误“找不到符号:方法start()和SlumpTal1的变量T1” 最佳答案
制作一个新类并执行它。
脚步:
创建一个新文件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();
}
}
执行应用
使用您的IDE(它将自动找到主要方法)
从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
关于java - 我应该在Main Method中添加什么以使程序可运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33778061/