您的位置:首页 > 其它

初始化了一个没有run()方法的线程类,是否会出错? (安邦)

2014-10-23 22:44 183 查看
要分情况:

第一种情况:通过继承Thread类来实现线程。这种方法,没有run(),编译、运行都不会报错。

public class TestThread

{

public static void main(String[] args)

{

AThread t = new AThread();
t.start();

System.out.println("没有编译运行异常");// 输出:没有编译运行异常

}

}

class AThread extends Thread //Thread类已经实现了空的run()方法。

{
//代码

}

第二种情况:通过Runnable接口实现线程,没有run()方法,编译会出现异常。原因是通过接口实现,该类必须重写Runnable接口中的抽象方法run()方法。

public class TestRunnable

{

public static void main(String[] args)

{

AThread t = new AThread();

Thread t1= new Thread(t);

t1.start();

System.out.println("编译运行没有错");

}

}

class AThread implements Runnable

{

public void run() //必须有此方法否则编译报错。它是Runnable接口中的抽象方法。

{

System.out.println(”run()方法”);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐