<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">线程池的使用有两种情况:</span>
1.执行Runnable对象
定义一个类实现Runnable接口,run()方法中是你要在线程中运行的代码
public class MyThread implements Runnable{
@Override
public void run() {
//在控制台中输出 当前线程名称:0-99
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
在main方法中的代码如下
//创建线程池,线程池中有两个线程
ExecutorService pool = Executors.newFixedThreadPool(2);
//添加线程
pool.submit(new MyThread());
pool.submit(new MyThread());
//停止线程池
pool.shutdown();
2.执行Callable对象
定义一个类实现Callable接口,run()方法中是你要在线程中运行的代码
import java.util.concurrent.Callable;
public class MyCallable implements Callable{
@Override
public Object call() throws Exception {
//在控制台中输出 当前线程名称:0-99
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
return null;
}
}
在main方法中的代码如下
//创建线程池,线程池中有两个线程
ExecutorService pool = Executors.newFixedThreadPool(2);
//添加线程
pool.submit(new MyCallable());
pool.submit(new MyCallable());
//停止线程池
pool.shutdown();
注:在使用时一般用第一种方法,第一种方法与第二种方法的区别是第二种方法run()中有返回值。