线程的创建
- Java语言的JVM允许程序运行多个线程,它通过java.lang.Thread 类来体现。
- Thread类的特性 :
- 每个线程都是通过某个特定Thread对象的run()方法来完成操作的,经常把run()方法的主体称为线程体。
- 通过该Thread对象的start()方法来启动这个线程,而非直接调用run()。
方式一:继承Thread类
- 定义子类继承Thread类。
- 子类中重写Thread类中的run()方法。
- 创建Thread子类对象,即创建了线程对象。
- 调用线程对象start()方法:启动线程,调用run()方法。
示例代码:
public class ThreadDemo {
public static void main(String[] args) {
MyThread mythread = new MyThread();
mythread.start();
for (int i = 0; i < 10; i++)
System.out.println("The thread 0 is running.");
}
}
class MyThread extends Thread {
public MyThread() {
super();
}
public void run() {
for (int i = 0; i < 10; i++)
System.out.println("The thread 1 is running.");
}
}
输出:
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 1 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 0 is running.
The thread 1 is running.
方式二:实现Runnable接口
- 定义子类,实现Runnable接口。
- 子类中重写Runnable接口中的run()方法。
- 通过Thread类含参构造器创建线程对象。
- 将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。
- 调用Thread类的start()方法:开启线程,调用Runnable子类接口的run()方法。
public class ThreadDemo {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
Thread t1 = new Thread(myThread1);
Thread t2= new Thread(myThread1);
t1.start();
t2.start();
for (int i = 0; i < 10; i++)
System.out.println(String.format("%s : is running.", Thread.currentThread().getName()));
}
}
public class MyThread1 extends Thread implements Runnable {
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(String.format("%s : is running.", Thread.currentThread().getName()));
}
}
Thread-1 : is running.
main : is running.
Thread-1 : is running.
Thread-2 : is running.
Thread-1 : is running.
main : is running.
Thread-1 : is running.
main : is running.
Thread-2 : is running.
Thread-1 : is running.
Thread-2 : is running.
继承方式和实现方式的联系与区别:
public class Thread extends Object implements Runnable
- 区别
- 继承Thread:线程代码存放Thread子类run()方法中。
- 实现Runnable:线程代码存在接口的子类的run()方法。
- 实现方式的好处
- 避免了单继承的局限性 。
- 多个线程可以共享同一个接口实现类的对象,非常适合多个相同线程来处理同一份资源。
方式三: 实现Callable接口
与Runnable相比
- 相比run()方法,可以有返回值
- 方法可以抛出异常
- 支持泛型的返回值
- 需要借助FutureTask类,比如获取返回结果
Future接口
- 可以对具体Runnable、Callable任务的执行结果进行取消、查询是否完成、获取结果等。
- FutrueTask是Futrue接口的唯一的实现类
- FutureTask 同时实现了Runnable, Future接口。它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值
方式四:使用线程池
背景:
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程, 对性能影响很大.
思路:
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
优点:
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理
示例代码:
import java.util.concurrent.*;
public class ThreadCallable {
public static void main(String[] args) {
CounterTen ct = new CounterTen();
FutureTask ft = new FutureTask(ct);
new Thread(ft).start();
try {
System.out.println(ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class CounterTen implements Callable {
@Override
public Object call() throws Exception {
int[] s = new int[10];
for (int i = 0; i < 10; i++) {
s[i] = i;
Thread.sleep(200);
System.out.println(Thread.currentThread().getName() + " " + i);
}
return s;
}
}
输出:
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-0 7
Thread-0 8
Thread-0 9
[I@1e643faf
线程池相关API
JDK5.0起提供了线程池相关API:ExecutorService和Executors
- ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
- <T>Future<T> submit(Callable<T> task):执行任务,有返回值,一般又来执行Callable
- void shutdown():关闭连接池
- Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
- Executors.newCachedThreadPool():创建一个可根据需要创建新线程的线程池
- Executors.newFixedThreadPool(n);创建一个可重用固定线程数的线程池
- Executors.newSingleThreadExecutor():创建一个只有一个线程的线程池
- Executors.newScheduledThreadPool(n):创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
示例代码:
import java.util.concurrent.*;
public class ThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(10);
ShowOdd so = new ShowOdd();
ShowEven se = new ShowEven();
es.execute(so);
FutureTask ft = new FutureTask(se);
es.submit(ft);
Object obj =ft.get();
System.out.println(obj);
es.shutdown();
}
}
class ShowOdd implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 1) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
class ShowEven implements Callable {
private int[] s = new int[5];
@Override
public Object call() throws Exception {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
s[i/2] = i;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
return s;
}
}
输出:
pool-1-thread-1: 1
pool-1-thread-2: 0
pool-1-thread-2: 2
pool-1-thread-1: 3
pool-1-thread-2: 4
pool-1-thread-1: 5
pool-1-thread-2: 6
pool-1-thread-1: 7
pool-1-thread-1: 9
pool-1-thread-2: 8
[I@2812cbfa