概述
1、继承Thread
2、实现Runable接口
3、实现Callable接口通过FutureTask包装器来创建Thread线程
4、通过Executor框架实现多线程的结构化,即线程池实现。(该实现方式将会下一篇单独介绍)
1、继承Thread
class CreateThreadByExtendThread extends Thread {
public CreateThreadByExtendThread(String name) {
super(name);
}
@Override
public void run() {
for(int i=0;i<=2;i++) {
System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
}
}
}
2、实现Runable接口
class CreateThreadByImpleRunable implements Runnable{
@Override
public void run() {
for(int i=0;i<=2;i++) {
System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
}
} }
执行CreateThreadByExtendThread和CreateThreadByImpleRunable
public class CreateThread { public CreateThread() {
// TODO Auto-generated constructor stub
}
/**
* <p>
* 测试并发编程实现方式
* </p>
* @param args
*/
public static void main(String[] args) {
CreateThreadByExtendThread ctetThread = new CreateThreadByExtendThread("AAAA");
ctetThread.start();
Thread ctbrThread = new Thread(new CreateThreadByImpleRunable(),"BBBB");
ctbrThread.start();
}
}
执行结果
上述是无返回结果的线程,二者区别:Thread类实现了Runable接口。从代码灵活性的角度考虑建议使用第二种方式。
3、实现Callable接口通过FutureTask包装器来创建Thread线程
class CreateThreadByImpleCallable<String> implements Callable<String>{
private CreateThreadByImpleCallable<String> ctbc = null;
@Override
public String call() throws Exception {
for(int i=0;i<=2;i++) {
System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
}
return (String) "Game over";
}
public String getTask() throws InterruptedException, ExecutionException {
ctbc = ctbc == null ? new CreateThreadByImpleCallable<String>() : ctbc;
FutureTask<String> ftTask = new FutureTask<String>(ctbc);
Thread ftThread = new Thread(ftTask,"CCCC");
ftThread.start();
return ftTask.get();
} }
上述main方法添加此行代码
try {
System.out.print(new CreateThreadByImpleCallable<String>().getTask());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}