Eclipse Java线程
线程上的Java程序,看起来还可以,但在Eclipse Java线程,java,multithreading,Java,Multithreading,线程上的Java程序,看起来还可以,但在UserThread ut1=newuserthread(5,“thread A”) 节目: public class Ch10_2_2 { class UserThread extends Thread { private int length; public UserThread(int length, String name){ super(name); thi
UserThread ut1=newuserthread(5,“thread A”)代码>
节目:
public class Ch10_2_2 {
class UserThread extends Thread {
private int length;
public UserThread(int length, String name){
super(name);
this.length = length;
}
public void run() {
int temp = 0;
for (int i = 1; i <= length; i++) temp += i;
System.out.println(Thread.currentThread() + "Sum = " + temp);
}
}
public static void main(String[] args) {
System.out.println("Thread: " + Thread.currentThread());
UserThread ut1 = new UserThread(5, "Thread A");
UserThread ut2 = new UserThread(5, "Thread B");
ut1.start(); ut2.start();
}
}
公共类Ch10_2_2{
类UserThread扩展线程{
私有整数长度;
公共用户线程(int长度,字符串名称){
超级(姓名);
这个长度=长度;
}
公开募捐{
内部温度=0;
对于(inti=1;i您应该将UserThread
类更改为static
当前,您试图从静态上下文访问“实例”类,这是无效的。将嵌套类设置为静态将允许您从静态上下文访问它,而不会出错
有关详细信息,请参阅。将其设置为静态类。静态类UserThread…
确切地说:)非常感谢!为什么会被否决?这是正确的解决方案。如果内部
类是静态的,那么只有一个对吗?因为OP以非线程安全的方式实例化了其中两个,所以这不是他想要的解决方案。@Wombat:这是不正确的。不管一个类是否定义为静态的类加载器中只有一个定义。区别在于引用该定义的方式。如果嵌套类不是静态的,则不能直接引用。需要外部类的实例,即NestedClass c=new OuterClass()。new NestedClass()