学习线程时那编写的小程序出现的问题
程序代码
public class ThreadDemo
{
public static void main(String[] args)
{
TestThread t=new TestThread();
t.start();
{System.out.println("main");}
}
class TestThread extends Thread
{
private int ticket=100;
public void run()
{
while(true)
if(ticket>0)
System.out.println(Thread.currentThread().getName()+"is running"+ticket--);
}
}
}
错误类型
无法从静态上下文中引用非静态 变量 this
错误原因
将 class TestThread 设为内部类
改正方法
将类 class TestThread从类ThreadDemo中分出来,即可解决问题
本文探讨了在Java线程编程中遇到的一个常见错误:无法从静态上下文中引用非静态变量,并提供了解决方法。通过将内部类从静态方法中分离出来,可以解决此问题。
8211

被折叠的 条评论
为什么被折叠?



