程序
進程:運行的程序
線程:進程中負責程序執行的執行單元,一個進程至少包括一個線程。
單線程:一個進程一個線程
多線程:一個進程多個線程
多線程是爲了更好的利用CPU,提高程序運行的速度。
實現方式:繼承Thread類、實現Runnable接口
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread{
private static int num = 0;
public MyThread(){
num++;
}
@Override
public void run() {
System.out.println("主動創建的第"+num+"個線程");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("主線程ID:"+Thread.currentThread().getId());
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
class MyRunnable implements Runnable{
public MyRunnable() {
}
@Override
public void run() {
System.out.println("子線程ID:"+Thread.currentThread().getId());
}
}
start方法和run方法的區別:start會創建新線程,run這是普通的方法調用,不會創建新線程。
public class Test {
public static void main(String[] args) {
System.out.println("主線程ID:"+Thread.currentThread().getId());
MyThread thread1 = new MyThread("thread1");
thread1.start();
MyThread thread2 = new MyThread("thread2");
thread2.run();
}
}
class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
System.out.println("name:"+name+" 子線程ID:"+Thread.currentThread().getId());
}
}
Java多線程
帶返回結果之Executor
package threadtst;
import java.util.Date;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Object> {
private String taskNum;
MyCallable(String taskNum){
this.taskNum = taskNum;
}
@Override
public Object call() throws Exception {
System.out.println(">>>"+taskNum+"任務啓動");
Date date1 = new Date();
Thread.sleep(1000);
Date date2 = new Date();
long time = date1.getTime()-date2.getTime();
System.out.println(">>>"+taskNum+"任務終止");
return taskNum+"任務運行時間"+time+"毫秒";
}
}
package threadtst;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExceutorTst {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<Future>();
for(int i=0;i<taskSize;i++){
Callable c = new MyCallable(i+"");
Future f = pool.submit(c);
list.add(f);
}
pool.shutdown();
for(Future f: list){
System.out.println(f.get().toString());
}
}
}
運行結果
>>>0任務啓動
>>>2任務啓動
>>>1任務啓動
>>>3任務啓動
>>>4任務啓動
>>>1任務終止
>>>3任務終止
>>>4任務終止
>>>0任務終止
>>>2任務終止
0任務運行時間-1001毫秒
1任務運行時間-1001毫秒
2任務運行時間-1001毫秒
3任務運行時間-1001毫秒
4任務運行時間-1001毫秒
線程狀態
五種
new
runnable
running
blocked
dead