1.1线程的创建与运行
创建线程的方式有三种:1.继承Thread类、2.实现Ruunable接口、3.futrueTask方法。
1.1.1 Thread类的实现和运行
/**
* @date 2020-1-21
* @author 49800
*/
public class ThreadTest {
public static class MyThread extends Thread{
@Override
public void run() {
System.out.println("I am a child thread");
String name = this.getName();
System.out.println(name);
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
MyThread myThread1 = new MyThread();
myThread.start();
myThread1.start();
}
}
好处: 想要获取线程直接就可以使用this获取到。
坏处: 因为是抽象类,所以当类继承Thread时候就不能继承其他的类了。当多线程使用同一个代码的时候,这样可能需要多次写那些逻辑代码。
1.1.2 Runnable接口
/**
* @date 2020-1-21
* @author 49800
*/
public class RunnableTest implements Runnable{
@Override
public void run() {
System.out.println("我是一个runnable线程");
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
RunnableTest runnableTest = new RunnableTest();
new Thread(runnableTest).start();
new Thread(runnableTest).start();
}
}
好处: 因为是接口,所以可以多实现,还可以继承一个抽象类,这样更加灵活。还可以根据RunnableTest类设置自己的属性来进行同一业务代码进行不同属性下的操作。
坏处: Thread 抽象类 和 Runnable接口 都是没有返回值。
1.1.3 FutrueTask 方式
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @date 2020-1-21
* @author 49800
*/
public class CallableTest implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("我是Callable线程,我有返回值");
return "null";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> stringFutureTask = new FutureTask<>(new CallableTest());
new Thread(stringFutureTask).start();
// 可以根据get()方法来获取返回得值
String s = stringFutureTask.get();
System.out.println(s );
}
}
总结:
使用继承方式的好处是方便传参,你可以在子类里面添加成员变量,通过set方法设置参数或者通过构造函数进行传递,而如果使用Runnable方式,则只能使用主线程里面被声明为final的变量。不好的地方是Java不支持多继承,如果继承了Thread类,那么子类不能再继承其他类,而Runable则没有这个限制。前两种方式都没办法拿到任务的返回结果,但是Futuretask方式可以。