java多线程入门知识及示例程序
为什么需要多线程?
模型的简化,如某些程序是由多个相对独立任务的运行:
图形界面的出现,输入、输出的阻塞
多核CPU的更好利用
异步行为的需要
Java多线程的特性:
程序的入口main本身是一个线程
线程是并发的,无序执行的
线程内部是顺序执行的
共享数据
Java多线程的风险:
安全风险:由于线程的操作顺序是不确定的,某些在单线程下能运行的程序到多线程下会出现意外的结果。
性能风险:服务器的吞吐量、响应性、资源消耗
Java多线程API:
Java可以通过两种形式创建线程:一、实现Runnable接口,二、继承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() {
}
}
}