標籤:tar print trace += oid 傳回值 java string 繼承
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); } }}
第三種方式:使用Calable和Future建立具備傳回值的線程
package com.yyx.thread;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;/** * 使用Calable和Future建立具備傳回值的線程 yyx 2018年2月6日 */public class CreateThreadByCallable implements Callable<Integer> { public static void main(String[] args) { CreateThreadByCallable createThreadByCallable=new CreateThreadByCallable(); FutureTask<Integer> task=new FutureTask<Integer>(createThreadByCallable); new Thread(task,"有傳回值的線程").start(); try { System.out.println(task.get()); }catch (Exception e) { e.printStackTrace(); } } @Override public Integer call() throws Exception { Integer total=0; for(int i=1;i<=50;i++){ total+=i; } return total; }}
Java多線程Thread的建立