public class test {
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.setName("demo1");
threadDemo.start();
System.out.println("主线程:"+Thread.currentThread().getName());
}
}
public class ThreadDemo extends Thread{
@Override
public void run() {
System.out.println("继承Thread实现多线程,名称:"+Thread.currentThread().getName());
}
}
控制台输出
主线程:main 继承Thread实现多线程,名称:demo1
实现Runnable
public class test {
public static void main(String[] args) {
ThreadDemo2 threadDemo2 = new ThreadDemo2();
Thread thread = new Thread(threadDemo2);
thread.setName("demo2");
thread.start();
System.out.println("主线程名称:"+Thread.currentThread().getName());
}
}
public class ThreadDemo extends Thread{
@Override
public void run() {
System.out.println("继承Thread实现多线程,名称:"+Thread.currentThread().getName());
}
}
JDK8之后采用lambda表达式
public class test {
public static void main(String[] args) {
Thread thread = new Thread(()->{
System.out.println("通过Runnable实现多线程,名称:"+Thread.currentThread().getName());
});
thread.setName("demo2");
thread.start();
System.out.println("主线程名称:"+Thread.currentThread().getName());
}
}
控制台输出
主线程名称:main 通过Runnable实现多线程,名称:demo2
通过Callable和FutureTask方式
import java.util.concurrent.Callable;
public class MyTask implements Callable<Object> {
@Override
public Object call() throws Exception {
System.out.println("通过Callable实现多线程,名称:"+Thread.currentThread().getName());
return "这是返回值";
}
}
public class test {
public static void main(String[] args) {
FutureTask<Object> futureTask = new FutureTask<>(()->{
System.out.println("通过Callable实现多线程,名称:"+Thread.currentThread().getName());
return "这是返回值";
});
// MyTask myTask = new MyTask();
// FutureTask<Object> futureTask = new FutureTask<>(myTask);
//FutureTask继承了Runnable,可以放在Thread中启动执行
Thread thread = new Thread(futureTask);
thread.setName("demo3");
thread.start();
System.out.println("主线程名称:"+Thread.currentThread().getName());
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
//阻塞等待中被中断,则抛出
e.printStackTrace();
} catch (ExecutionException e) {
//执行过程发送异常被抛出
e.printStackTrace();
}
}
}
控制台输出
主线程名称:main 通过Callable实现多线程,名称:demo3 这是返回值
通过线程池创建线程
public class ThreadDemo4 implements Runnable {
@Override
public void run() {
System.out.println("通过线程池+runnable实现多线程,名称:"+Thread.currentThread().getName());
}
}
public class test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for(int i=0;i<10;i++){
executorService.execute(new ThreadDemo4());
}
System.out.println("主线程名称:"+Thread.currentThread().getName());
//关闭线程池
executorService.shutdown();
}
}