多线程
1、方式总结:
1 inherit Thread Class
public class CreateThreadDemo1 extends Thread {
public CreateThreadDemo1() {
// 设置当前线程的名字
this.setName("MyThread");
}
@Override
public void run() {
while (true) {
printThreadInfo();
try {
// 线程休眠一秒
Thread.sleep(1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws Exception {
// 注意这里,要调用start方法才能启动线程,不能调用run方法
new CreateThreadDemo1().start();
// 演示主线程继续向下执行
while (true) {
printThreadInfo();
Thread.sleep(1000);
}
}
/**
* 输出当前线程的信息
*/
private static void printThreadInfo() {
System.out.println("当前运行的线程名为: " + Thread.currentThread().getName());
}
}
2 implement Runnable interface
package com.kingh.thread.create;
/**
* 线程任务
*
* @author <a href="https://blog.csdn.net/king_kgh>Kingh</a>
* @version 1.0
* @date 2019/3/18 10:04
*/
public class CreateThreadDemo4_Task implements Runnable {
@Override
public void run() {
// 每隔1s中输出一次当前线程的名字
while (true) {
// 输出线程的名字,与主线程名称相区分
printThreadInfo();
try {
// 线程休眠一秒
Thread.sleep(1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* 输出当前线程的信息
*/
private static void printThreadInfo() {
System.out.println("当前运行的线程名为: " + Thread.currentThread().getName());
}
}
3 implement Callable and Future
1 、 创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值,可以抛出异常这两点也是和实现Runable接口这种方式的重要区别
2、 创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值
3、使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程
4、 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Author wz
* @Date 2019/9/3
* @Version 1.0
* <p>
* 通过实现Callable接口创建线程
*
* 实现Callable接口
* 1】创建Callable接口的实现类,并实现call()方法,然后创建该实现类的实例
* 2】使用FutureTask类来包装Callable对象,该FutureTask对象封装了Callable对象的call()方法的返回值
* 3】使用FutureTask对象作为Thread对象的target创建并启动线程(因为FutureTask实现了Runnable接口)
* 4】调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
* </p>
*/
public class MyThreadThree implements Callable<Integer> {
public static void main(String[] args) {
MyThreadThree myThreadThree = new MyThreadThree();
FutureTask<Integer> ft = new FutureTask<>(myThreadThree);
FutureTask<Integer> ft1 = new FutureTask<>(myThreadThree);
System.out.println(Thread.currentThread().getName() + "===== ");
new Thread(ft, "thread-1").start();
new Thread(ft1, "thread-2").start();
try {
System.out.println("return thread-1'result :" + ft.get());
System.out.println("return thread-2'result :" + ft1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public Integer call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return 20;
}
}