【发布时间】:2019-01-01 21:34:30
【问题描述】:
我需要使用线程来更改数组的元素。它应该随机更改(添加或减去整数)一个元素,休眠 2 秒并随机更改另一个。
所以我创建了我的数组和我的线程,但我不知道如何更改它。
public static void main(String[] args) {
int [] myarray= new int[5];
Thread x= new Thread();
x.start();
try
{
x.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public class myThread implements Runnable {
public myThread(){ //an empty constructor, to pass parameters
}
public void run(){
}
public void update(){ //i tohught i could use that for changing elements
}
【问题讨论】:
-
不相关:
x.sleep(2000)是错误代码。方法sleep是static,所以应该通过类名限定调用,而不是实例值,所以应该是Thread.sleep(2000) -
您需要将数组作为参数传递给构造函数。此外,您需要实际使用
myThread类。请注意,Java 命名约定是类名以大写字母开头,因此应称为MyThread。
标签: java arrays multithreading