ITeye博客

Java中实现多线程有两种方式

dir_murong · 2010-10-28 11:07 · core java · 编程语言 · Markdown

众所周知,在JAVA中实现多线程有两种方式:

一种是继承于Thread类

一种是实现Runnable接口

本质相同的实现机制,之所以有两种实现方式,一方面针对不同爱好的用户群体,另外可能是因为JAVA不支持多继承,一旦你的类已经继承一个父类就无法再继承Thread类了,这个时候只有实现Runnable接口。

示例代码如下:

继承

public class MyThread extends Thread{ private String thrName; public MyThread(String name){ this.thrName = name; } public void run(){ try { Thread.currentThread().sleep(50); System.out.println(this.thrName+" start"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }

} }

实现接口

public class MyThreadRunnable implements Runnable {

private String thrName; public MyThreadRunnable(String name){ this.thrName = name; } public void run() { // TODO Auto-generated method stub try { Thread.currentThread().sleep(25); System.out.println(this.thrName+" start"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。