java多線程入門常識及示例法式。本站提示廣大學習愛好者:(java多線程入門常識及示例法式)文章只能為提供參考,不一定能成為您想要的結果。以下是java多線程入門常識及示例法式正文
為何須要多線程?
模子的簡化,如某些法式是由多個絕對自力義務的運轉:
圖形界面的湧現,輸出、輸入的壅塞
多核CPU的更好應用
異步行動的須要
Java多線程的特征:
法式的進口main自己是一個線程
線程是並發的,無序履行的
線程外部是次序履行的
同享數據
Java多線程的風險:
平安風險:因為線程的操作次序是不肯定的,某些在單線程下能運轉的法式到多線程下會湧現不測的成果。
機能風險:辦事器的吞吐量、呼應性、資本消費
Java多線程API:
Java可以經由過程兩種情勢創立線程:1、完成Runnable接口,2、繼續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() {
}
}
}