為什麼需要多線程?
模型的簡化,如某些程序是由多個相對獨立任務的運行:
圖形界面的出現,輸入、輸出的阻塞
多核CPU的更好利用
異步行為的需要
Java多線程的特性:
程序的入口main本身是一個線程
線程是並發的,無序執行的
線程內部是順序執行的
共享數據
Java多線程的風險:
安全風險:由於線程的操作順序是不確定的,某些在單線程下能運行的程序到多線程下會出現意外的結果。
性能風險:服務器的吞吐量、響應性、資源消耗
Java多線程API:
Java可以通過兩種形式創建線程:一、實現Runnable接口,二、繼承Thread類。
繼承thread創建線程示例代碼
代碼如下:
public class ThreadTest extends Thread {
public static void main(String[] args) {
ThreadTest thread = new ThreadTest();
thread.start();
for (int i=0; i<10; i++) {
System.out.println("main:"+i);
}
}
@Override
public void run() {
for (int i=0; i<10; i++) {
System.out.println("thread:"+i);
}
}
}
實現runnable創建線程代碼
代碼如下:
package com.openrdp.thread.api;
public class RunnableTest implements Runnable {
public static void main(String[] args) {
RunnableTest runnable = new RunnableTest();
Thread thread = new Thread(runnable);
thread.start();
for (int i=0; i<10; i++) {
System.out.println("main:"+i);
}
}
@Override
public void run() {
for (int i=0; i<10; i++) {
System.out.println("thread:"+i);
}
}
}
Java線程池技術
Executors獲取exceuctorservice線程池代碼
代碼如下:
package com.openrdp.thread.api;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TreadPoolTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(99);
TaskThread thread1 = new TaskThread("t1");
threadPool.execute(thread1);
TaskThread thread2 = new TaskThread("t2");
threadPool.execute(thread2);
}
static class TaskThread implements Runnable {
String param;
public TaskThread(String param) {
this.param = param;
}
@Override
public void run() {
}
}
}