Thread 与 Runnable 混合使用测试
2024-08-22 17:58:14
package com.dava; public class TesThread extends Thread implements Runnable {
public void run() {
System.out.println("运行成功!");
} /**
* @param args
*/
public static void main(String[] args) {
Thread t=new Thread(new TesThread());
t.start(); } }
运行结果:
运行成功!
程序继承了Thread 实现Runnable,接口的方法是需要全部实现的,而Runnable接口源码如下:
public
interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
所以有run();方法程序会正常执行.
单独继承Runnable方法:
public class ImpInterface implements Runnable { public void run() {
// TODO Auto-generated method stub }
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("123465");
} }
如果部实现run方法会出现异常。但是在上面的ji集成了Thread又实现了Runnable,可以部实现Run方法,程序会正常运行。
package com.dava; public class TesThread extends Thread implements Runnable {
// public void run() {
// System.out.println("运行成功!");
// }
public void print() {
System.out.println("1231456"); }
/**
* @param args
*/
public static void main(String[] args) { // Thread t=new Thread(new TesThread());
// t.start();
new TesThread().print(); } }
运行结果:1231456
为什么不实现接口也行呢?看下图
Thread也实现了Runnable接口,实现了Run方法,子类默认继承了父类的方法,所以也实现了Runnable的run方法。
最新文章
- maven项目报:An error occurred while filtering resources
- prior knowledge
- tomcat错误:@HandlesTypes annotation of one or more ServletContentInitializers
- HDU1412
- WinForm(C#)CheckedlistBox绑定数据,并获得选中的值(ValueMember)和显示文本(DisplayMember)
- ASP.NET MVC学习之路由篇
- Linux系统环境变量的四个配置文件的关系
- WeChatAPI 开源系统架构详解
- Laravel 5.2 教程 - 数据填充
- CloseableHttpClient获取https请求不验证证书
- webpack 非严格模式设置 npm i babel-plugin-transform-remove-strict-mode
- 【转】python之配置日志的几种方式
- 弃 Java 而使用 Kotlin 的你后悔了吗?| kotlin将会是最好的开发语言
- shell 运算符
- poj1733(并查集+离散化)
- Effective Java 第三版——50. 必要时进行防御性拷贝
- shell 变量的数值计算实践 expr
- JVM 详解
- 2.5 Oracle之存储过程和MERGE INTO语句
- SQL数据是否存在(是否有数据)判断,表,存储过程是否存在