总共三种:
1.继承Thread:
a.子类继承Thread类;
b.重写子类的run方法;
c.将要执行的代码放在run()方法中;
d.创建子类的对象;
e.子类的对象调用.start()方法
2.实现Runnable接口
a.子类实现Runnable接口;
b.重写子类的run()方法;
c.将要执行的代码放在run()方法中;
d.将子类的对象传递给Thread的构造方法;
e.Thread的对象调用.start()方法.
第3种:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*
* 线程的第三种创建方式;
* */
public class Demo6_Callable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(2); //创建线程池
Future<Integer> f1 = pool.submit(new MyCallable(100)); //将线程放进池子里并执行
Future<Integer> f2 = pool.submit(new MyCallable(50));
System.out.println(f1.get());
System.out.println(f2.get());
pool.shutdown(); //关闭线程池
}
}
class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
public Integer call() throws Exception {
int sum = 0;
for(int i = 1;i <= num;i++) {
sum += i;
}
return sum;
}
}
|