实现多线程的几种方式
1、通过继承Thread类
public class test1 extends Thread{
private String name;
public test1(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.name+"正在执行"+i);
}
}
public static void main(String[] args) {
new test1("A").start();
new test1("B").start();
new test1("C").start();
}
}
优点:轻松实现,实例化对象之后,直接调用start方法即可。
缺点:Java单继承局限,所以一般不用
2、实现Runnable接口
public class test2 implements Runnable{
private String name;
public test2(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.name+"正在执行"+i);
}
}
public static void main(String[] args) {
test2 testA = new test2("A");
test2 testB = new test2("B");
test2 testC = new test2("C");
new Thread(testA).start();
new Thread(testB).start();
new Thread(testC).start();
}
}
优点:避免了单继承局限
缺点:实现有点繁琐
使用Lambda表达式简化实现Runnable接口
public class test3 {
public static void main(String[] args) {
new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println("a正在执行"+i);
}
}).start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println("b正在执行"+i);
}
}).start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println("c正在执行"+i);
}
}).start();
}
}
优点:简化操作,代码更简洁
缺点:lambda表达式现在还不会使
实现Callable接口,实现多线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class test4 implements Callable<String>{
String str = "";
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
this.str+="hello world\n";
}
return str;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
test4 test4 = new test4();
FutureTask<String> futureTask = new FutureTask<String>(test4);
Thread thread = new Thread(futureTask);
thread.start();
String h = futureTask.get();
System.out.println(h);
}
}
优点:避免了单继承局限,可以有返回值
缺点:实现有点繁琐
最后总结:实现多线程一般使用Callable接口或者Runnable接口,
如果有返回值就用Callable接口,无返回值就用Runnable接口。