Java创建线程的方式
方式一: 继承Thread类,重写run()方法
public class Test_Thread {
public static void main(String[] args) {
new Thread_Demo().start();
new Thread_Demo().start();
new Thread_Demo().start();
}
}
/**
* 创建线程的方式一:
* 继承 Thread 类,并重写 run() 方法
*/
class Thread_Demo extends Thread{
@Override
public void run() {
for(int i = 0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ", i = " + i);
}
}
}
方式二: 实现Runnable接口
import java.util.concurrent.TimeUnit;
public class Test_Runnable {
public static void main(String[] args) {
// 写法一,new一个Runnable的实现类对象作为构造入参
new Thread(new Runnable_Demo()).start();
new Thread(new Runnable_Demo()).start();
new Thread(new Runnable_Demo()).start();
try {
// 休眠1秒
TimeUnit.SECONDS.sleep(1);
// 写法二, 函数式编程
new Thread(()->{
for(int i = 0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ", i = " + i);
}
}).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 方式二:实现接口Runnable
* 作为Thread的构造入参来启动
*/
class Runnable_Demo implements Runnable{
@Override
public void run() {
for(int i = 0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ", i = " + i);
}
}
}
方式三: Callable与Future结合
在方式一与方式二中都无法直接获得线程的返回结果,只能通过共享变量等方法;使用Callable和Future方法可以获取到线程的执行结果。
import java.util.Random;
import java.util.concurrent.*;
public class Test_Callable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 普通写法
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Integer> submit = executorService.submit(new Callable_Demo());
Integer result = submit.get();
System.out.println("result is " + result);
// 函数式编程
Integer futureRes = executorService.submit(()->{
int res = new Random().nextInt();
System.out.println("Random is " + res + ", call method2 is running... ");
return res;
}).get();
System.out.println("futureRes is " + futureRes);
// 关闭服务
executorService.shutdown();
// 关闭服务后不能再新增线程到线程池中,下面代码在运行中会报错
executorService.submit(()->{
System.out.println("1245");
});
}
}
/**
* 方式三 实现Callable接口,可以获取线程的执行结果
* 需要结合Future和Executor*来实现
*/
class Callable_Demo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int result = new Random().nextInt();
System.out.println("Random is " + result + ", call method is running... ");
return result;
}
}