您的位置:首页 > 编程语言 > Java开发

继承接口Java多线程(二)、启动一个线程的3种方式

2013-05-19 21:11 274 查看
查了好多资料,发现还是不全,干脆自己整理吧,至少保证在我的做法正确的,以免误导读者,也是给自己做个记录吧!

package org.study.thread;

/**
* 启动一个线程的3种方式
*/
public class TraditionalThread {

public static void main(String[] args) {
// 1. 继承自Thread类(这里应用的是匿名类)
new Thread(){
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("threadName: " + Thread.currentThread().getName());
}
};
}.start();

// 2. 实现Runnable接口(这里应用的是匿名类)
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("threadName: " + Thread.currentThread().getName());
}
}
}).start();

// 3.即实现Runnable接口,也继承Thread类,并重写run方法
new Thread(new Runnable() {
@Override
public void run() {	// 实现Runnable接口
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("implements Runnable thread: " + Thread.currentThread().getName());
}
}
}) {	// 继承Thread类
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("extends Thread thread: " + Thread.currentThread().getName());
}
}
}.start();
}
}

每日一道理

翻开早已发黄的页张,试着寻找过去所留下的点点滴滴的足迹。多年前的好友似乎现在看来已变得陌生,匆忙之间,让这维持了多年的友谊变淡,找不出什么亲切感,只是偶尔遇上,淡淡地微笑,如今也只能在这发黄的页张中找寻过去的那些让人难忘的,至少我可以握住这仅剩下一段的“丝线头”……

执行结果:

threadName: Thread-0

threadName: Thread-1

extends Thread thread: Thread-2

threadName: Thread-1

threadName: Thread-0

extends Thread thread: Thread-2

threadName: Thread-1

threadName: Thread-0

extends Thread thread: Thread-2

。。。

文章结束给大家分享下程序员的一些笑话语录:

很多所谓的牛人也不过如此,离开了你,微软还是微软,Google还是Google,苹果还是苹果,暴雪还是暴雪,而这些牛人离开了公司,自己什么都不是。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐