一、实现多线程的方法
- 继承Thread类
- 实现Runnable接口
- 使用ExecutorService、Callable、Future实现有返回结果的多线程----多线程可以有返回值。
int taskSize = 5;
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
// 执行任务并获取Future对象
Future f = pool.submit(c);
// System.out.println(">>>" + f.get().toString());
list.add(f);
}
// 关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从Future对象上获取任务的返回值,并输出到控制台
System.out.println(">>>" + f.get().toString());
} `
需要返回值的必须实现Callable,不需要返回值的必须实现Runnable。
二、Thread与Runnable区别
- Thread是类,类只能单继承
- Runnable是接口,接口可以多实现
- Runnable可以进行数据共享:
//Runnable
class TestThread implements Runnable{
private int ticket=5;
private String name;
public TestThread(String name){
this.name=name;
}
public void run(){
for(int i=1;i<=10;i++){
if(ticket>0){
System.out.println("线程"+name+"卖票"+(ticket--));
}
}
}
}
public class Demo
{
public static void main(String args[]){
TestThread T = new TestThread ("name");
Thread T1 = new Thread(T );
Thread T2 = new Thread(T );
T1.start();
T2.start();
}
}
//Thread
class TestThread extends Thread
{
private int ticket=5;
private String name;
public TestThread (String name ){
this.name=name;
}
public void run(){
for(int i=0;i<10;i++){
if(ticket>5){
System.out.println("线程"+name+"卖票"+i);
}
}
}
}
public class Demo
{
public static void main(String args[]){
TestThread A = new TestThread("name1");
TestThread B = new TestThread("name2");
A.start();
B.start();
}
}
抛开运行结果不看,只看上面Thread和Runnable同类Demo的地方,在这里想想为啥说数据共享。
三、Runnable和Thread,run()结束后会自动停止吗?
当线程执行完毕或被其它线程杀死,线程就进入死亡状态,这时线程不可能再进入就绪状态等待执行。
自然终止:正常运行run()方法后终止
异常终止:调用stop()方法让一个线程终止运行或者通过interrupt