一 .继承Thread类
simple:
public class test01 {
@Test
public void thread01(){
for(int i = 0; i < 10; i++){
Business business = new Business();
Thread thread = new Thread(business);
thread.start();
}
}
class Business extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}
result :
PS :
1. java是单继承,所以用继承Thread实现多线程必须确保该类不继承其他类
二.实现Runnable接口
simple:
public class test02 {
@Test
public void thread02(){
for(int i = 0; i < 10; i++){
Business business = new Business();
Thread thread = new Thread(business);
thread.start();
}
}
class Business implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}
result :
PS:
1.实现Runnable接口得到的结果与直接使用Thread得到的结果无异。
2.实现runnable实现多线程,没有返回值,核心方法为run方法,不能抛出异常
3.Runnable实现多线程没有返回值,若需要做数据统计可使用Callable实现多线程,若情况特殊可参考《实现Runnable的多线程数据统计》。
三.实现Callable接口(两种方式)
1).用FutureTask实现
simple:
public class test04 {
@Test
public void thread04() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
List<FutureTask> futureTasks = new ArrayList<>();
for(int i = 0;i < 10; i++){
Business business = new Business("hello" + i);
FutureTask task = new FutureTask(business);
executor.execute(task);
futureTasks.add(task);
}
for(FutureTask future:futureTasks){
System.out.println(future.get());
}
}
class Business implements Callable<String>{
private String threadStr;
Business(String str){
this.threadStr = str;
}
@Override
public String call() throws Exception {
Thread.sleep(1000);
return Thread.currentThread().getName() + " say:" + threadStr;
}
}
}
result :
2).用Future实现
simple:
public class test03 {
@Test
public void thread03() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Future> futures = new ArrayList<>();
for(int i = 0;i < 10; i++){
Business business = new Business("hello" + i);
Future<String> future = executor.submit(business);
futures.add(future);
}
for(Future future:futures){
System.out.println(future.get());
}
}
class Business implements Callable<String>{
private String threadStr;
Business(String str){
this.threadStr = str;
}
@Override
public String call() throws Exception {
Thread.sleep(1000);
return Thread.currentThread().getName() + " say:" + threadStr;
}
}
}
result:
PS :
1.callable<V>可以拥有返回值,所以一般用来统计或计算,核心方法为call方法,可以抛出异常。
2.不要直接在子线程未启动完之前get(),否则就与单线程无异。
3.尽量配合使用线程池,虽然FutureTask也可以作为Runnable传到Thread()中.
4.使用ExecutorService创建线程池请参考《线程池详解》。