三种线程创建方法介绍
继承Thread
优点:可以直接使用Thread类中的方法,代码简单
缺点:继承Thread类之后就不能继承其他的类
实现Runnable接口
优点:即时自定义类已经有父类了也不受影响,因为可以实现多个接口
缺点: 在run方法内部需要获取到当前线程的Thread对象后才能使用Thread中的方法
实现Callable接口
优点:可以获取返回值,可以抛出异常
缺点:代码编写较为复杂
其他的不多说,直接上代码
继承Thread
package com.thy.classloader;
//继承java.lang包下的Thread类
class MyThread extends Thread{
//重写run方法
@Override
public void run() {
//编写线程代码
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread());
}
}
}
//编写启动类,测试编写的MyThread类
public class BaseMultithreading {
public static void main(String[] args) {
//new自定义的MyThread类
MyThread mt = new MyThread();
MyThread mt1 = new MyThread();
//调用start方法启动线程
mt.start();
mt1.start();
for(int i = 0; i< 10; i++) {
System.out.println("I am main");
}
}
}
运行结果
实现Runnable接口
package com.thy.classloader;
//实现java.lang包下的Runnable接口
class MyRunnable implements Runnable{
//编写run方法
@Override
public void run() {
//编写需要实现的代码块
System.out.println(Thread.currentThread());
}
}
//编写启动类,测试编写的MyRunnable类
public class BaseMultithreading {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
//创建Thread对象并将上面MyRunnable类的对象作为参数传递给Thread的构造方法
Thread thread = new Thread(myRunnable);
Thread thread1 = new Thread(myRunnable);
//调用start方法启动线程
thread.start();
thread1.start();
System.out.println("I am main");
}
}
运行结果
实现Callable接口
package com.thy.classloader;
import java.util.concurrent.*;
//编写启动类,测试编写的MyCallable类
public class BaseMultithreadingRunable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//MyCallable类的对象
ExecutorService exec = Executors.newCachedThreadPool();
MyCallable myCallable= new MyCallable();
//执行方法
Future future = exec.submit(myCallable);
//获取返回的值并打印出来
System.out.println(future.get());
}
}
//自定义一个类实现Callable接口
class MyCallable implements Callable {
//编写call方法
@Override
public String call() throws Exception{
System.out.println("call方法执行了");
return "call方法返回值";
}
}
运行结果