文章目录
- Java 开启多线程详细教程
- 简介
- 1. 实现 Runnable 接口
- 2. 实现 Callable 接口
- 3. 继承 Thread 类
- 4. 匿名内部类的写法
简介
常见的4种使用线程的方法:
- 1实现 Runnable 接口;
- 2实现 Callable 接口;
- 3继承 Thread 类。
- 4匿名内部类的写法。
- 编写测试类RunnableDemo 实现 Runnable 接口,实现接口中的 run() 方法。
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行了");
}
public static void main(String[] args) {
RunnableDemo runnable = new RunnableDemo();
Thread thread0 = new Thread(runnable);
Thread thread1 = new Thread(runnable);
thread0.start();
thread1.start();
}
}
- 运行main方法
- 与 Runnable 相比,Callable 可以有返回值,返回值通过 FutureTask 进行封装。
public class CallableDemo implements Callable{ @Override public String call() { System.out.println(Thread.currentThread().getName() + "执行了"); return "执行成功!"; } public static void main(String[] args) throws ExecutionException, InterruptedException { CallableDemo mc = new CallableDemo(); FutureTask ft0 = new FutureTask<>(mc); FutureTask ft1 = new FutureTask<>(mc); Thread thread0 = new Thread(ft0); Thread thread1 = new Thread(ft1); thread0.start(); thread1.start(); System.out.println(ft0.get()); System.out.println(ft1.get()); } }
- 启动main方法
- 同样也是需要实现 run() 方法,因为 Thread 类也实现了 Runable 接口。
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行了");
}
public static void main(String[] args) {
ThreadDemo thread0 = new ThreadDemo();
ThreadDemo thread1 = new ThreadDemo();
thread0.start();
thread1.start();
}
}
- 启动main方法
- new Runnable()是一个实现接口Runnable的类的对象,后面的run()方法是该类里实现的方法,这就是匿名内部类的写法
public class ThreadTest {
public static void start() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行了");
}
}).start();
}
public static void main(String[] args) {
start();
start();
}
}



