閱讀18 返回首頁    go 微軟 go windows


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

。。。


最後更新:2017-04-03 18:51:58

  上一篇:go HashCode的作用
  下一篇:go Android旋轉屏幕研究