1. 程式人生 > >Java線程Thread的創建

Java線程Thread的創建

print eth ride 設置 reat adb xtend .get args

Java中線程的創建有兩種方式:

1. 通過繼承Thread類,重寫Thread的run()方法,將線程運行的邏輯放在其中

2. 通過實現Runnable接口,實例化Thread類

第一種方式:繼承Thread類

package com.yyx.thread;
/**
 * 通過繼承Thread類創建線程
 * yyx 2018年2月4日
 */
public class CreateThreadByextends {
    public static void main(String[] args) {
        ExtendThread extendThread = new
ExtendThread();
extendThread.setName("線程一");//設置線程名稱 extendThread.start();
for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } class ExtendThread extends Thread { @Override public void run() {
for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }

第二種方式:實現Runnable接口

package com.yyx.thread;
/**
 * 推薦:通過實現Runnable接口創建線程
 * yyx 2018年2月4日
 */
public class CreateThreadByInterface {
    public static void main(String[] args) {
        SubThread subThread
=new SubThread(); Thread thread=new Thread(subThread, "線程一"); thread.start();//一個線程只能夠執行一次start() for(int i = 1;i <= 100;i++){ System.out.println(Thread.currentThread().getName() +":" + i); } } } class SubThread implements Runnable { @Override public void run() { for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }

Java線程Thread的創建