继承接口Java多线程(二)、启动一个线程的3种方式
查了好多资料,发现还是不全,干脆自己整理吧,至少保证在我的做法正确的,以免误导读者,也是给自己做个记录吧!
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,苹果还是苹果,暴雪还是暴雪,而这些牛人离开了公司,自己什么都不是。