Java創建線程依賴java.lang.Thread類
package com.wkcto.chapter07.newthread;
/**
* 演示創建線程的方式一
* 定義Thread類的子類
* @author 蛙課網
*
*/
public class Test01 {
public static void main(String[] args) {
//3)創建線程對象
SubThread t1 = new SubThread();
//4) 開啟線程
t1.start(); //開啟的線程會執行run()方法
// t1.run(); //就是普通實例方法的調用, 不會開啟新的線程
//當前線程是main線程
for( int i = 1; i<=100; i++){
System.out.println( "main : " + i);
}
/*
* 每次運行程序, 運行的結果可能不一樣
* 運行程序后, 當前程序就有兩個線程main線程和t1線程在同時執行, 這兩個線程中哪個線程搶到CPU執行權, 這個線程就執行
*
* 在單核CPU中, 在某一時刻CPU只能執行一個任務, 因為CPU執行速度非常快, 可以在各個線程之間進行快速切換
* 對于用戶來說, 感覺是多個線程在同時執行
*
*/
}
}
//1)定義類繼承Thread
class SubThread extends Thread{
//2)重寫run(), run()方法中的代碼就是子線程要執行的代碼
@Override
public void run() {
//在子線程中打印100行字符串
for( int i = 1; i<=100 ; i++){
System.out.println("sub thread -->" + i);
}
}
}
定義Runnable接口的實現類
package com.wkcto.chapter07.newthread;
/**
* 創建線程的方式二
* 實現Runnable接口
* @author 蛙課網
*
*/
public class Test02 {
public static void main(String[] args) {
//3) 創建線程對象, 調用構造方法 Thread(Runnable) , 在調用時, 傳遞Runnable接口的實現類對象
Prime p = new Prime(); //創建Runnable接口的實現類對象
Thread t2 = new Thread(p);
//4) 開啟線程
t2.start();
//通過Runnable接口匿名內部類的形式創建線程
Thread t22 = new Thread(new Runnable() {
@Override
public void run() {
for( int i = 1; i <= 100; i++){
System.out.println("t22==> " + i);
}
}
});
t22.start();
// 當前線程是main線程
for (int i = 1; i <= 100; i++) {
System.out.println("main : " + i);
}
}
}
//1) 定義一個類實現Runnable接口
class Prime implements Runnable{
//2)重寫run()方法, run()方法中的代碼就是子線程要執行的代碼
@Override
public void run() {
// 在子線程中打印100行字符串
for (int i = 1; i <= 100; i++) {
System.out.println("sub thread -->" + i);
}
}
}
定義Callable接口的實現類
package com.wkcto.chapter07.newthread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 創建線程的方式三
* 實現Callable接口
* @author 蛙課網
*
*/
public class Test03 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//3)創建線程對象
Prime2 p2 = new Prime2(); //創建Callable接口的實現類對象
FutureTask<Integer> task = new FutureTask<>( p2 ); //創建FutureTask對象
//FutureTask類實現了RunnableFuture接口, 該接口繼承了Runnable接口, FutureTask類就是Runnable接口的實現類
Thread t3 = new Thread(task);
//4)開啟線程
t3.start();
// 當前線程是main線程
for (int i = 1; i <= 100; i++) {
System.out.println("main : " + i);
}
//在main線程中可以取得子線程的返回值
System.out.println(" task result : " + task.get() );
}
}
//1)定義類實現Callable接口
//Callable接口的call()方法有返回值, 可以通過Callable接口泛型指定call()方法的返回值類型
class Prime2 implements Callable<Integer> {
//2)重寫call()方法, call()方法中的代碼就是子線程要執行的代碼
@Override
public Integer call() throws Exception {
//累加1~100之間的整數和
int sum = 0 ;
for(int i = 1; i<=100; i++){
sum += i;
System.out.println("sum=" + sum);
}
return sum;
}
}