1.线程池
创建和销毁大量的线程,开销很大。
所以可以使用线程池,提取创建好多个线程,使用时直接获取,使用完毕后放回线程池中,避免了大量的创建和销毁操作。
优点:
- 提高响应速度
- 降低资源消耗
- 便于线程管理
具体实现:
Runnable接口的线程:
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class D26 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
service.execute(new TestThread());
service.execute(new TestThread());
service.execute(new TestThread());
service.shutdown();
}
}
class TestThread implements Runnable{
@Override
public void run() {
System.out.println("This is " + Thread.currentThread().getName() );
}
}
Callable接口的线程:
import java.util.concurrent.*;
public class D27 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
Future<Integer> r1 = service.submit(new Test2());
Future<Integer> r2 = service.submit(new Test2());
Future<Integer> r3 = service.submit(new Test2());
service.shutdown();
}
}
class Test2 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("This is " + Thread.currentThread().getName());
return 0;
}
}