Java线程创建的四种方式
java提供多线程的支持,就是在一个进程内并罚执行多个线程,每个线程都执行不同的任务,常见的Java创建线程的方式有
1.继承Thread类
2.实现runnable借口
3.通过Executor和Callable实现所有返回值的线程
4. 基于线程池创建
继承Thread类
Thread类实现了Runnable接口,并定义了一些操作线程的方法,可以通过继承Thread类来实现多线程。
他的使用步骤是创建一个类继承Thread接口,然后实例化这个类并且调用start方法,
start方法其实是一个native方法,通过在操作系统上启动一个新线程,最终执行run方法来启动线程。run方法是线程类的具体实现。
class NewThread extends Thread{
public void run(){
System.out.println("creaty a thread by this class exnteds Thread class");
}
}
public class Application {
public static void main(String[] args) {
NewThread newThread = new NewThread();
newThread.start();
}
}
实现runnable对象
实现runnable借口创建线程,重写run方法,然后创建该线程的实例在调用start方法
class NewThread1 implements Runnable{
@Override
public void run() {
System.out.println("creaty a thread by this class implements the runnable");
}
}
public class Application {
public static void main(String[] args) {
NewThread1 newThread1 = new NewThread1();
newThread1.run();
}
}
通过ExecutorService和Callable实现有返回值的线程
他的实现过程为创建一个类实现Callable接口,重写call方法,
它的调用过程为,创建一个线程池,创建一个用来接受futrue list和一个用来借口callable实例,使用线程池提交任务,并将任务的返回结果保存在futrue中,线程执行完毕后就便利Future List中的Future对象,在该对象上调用get方法就可以获取callable线程任务的返回结果。
class Mycallable implements Callable<String>{
String name ;
public Mycallable(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
return this.name;
}
}
public class Application {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//创建有返回值的任务列表
List<Future> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Callable c = new Mycallable(i+"thread");
Future f = pool.submit(c);
list.add(f);
}
pool.shutdown();
for (Future future : list) {
System.out.println(future.get().toString());
}
}
}
使用线程池创建线程
线程是非常宝贵的资源,每次创建和销毁都会浪费大量的资源,我们可以使用缓存策略并使用线程池来创建资源,此过程就是创建一个线程池提交线程任务
public class Application {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}
}