Java创建线程的方式及实现
Java创建线程的方式主要有以下三种
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
继承Thead类
- 创建继承自Thread类的子类并重写Thread类的run方法
- 通过创建该子类的对象,获得线程对象
- 调用线程对象的start()方法启动线程
package com.demo.thread;
public class ThreadDemo extends Thread {
public ThreadDemo(String name) {
super(name);
}
@Override
public void run() {
int i = 100;
while (i-- > 0) {
System.out.println(String.format("%s:第%d次运行", getName(), i));
}
}
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo("A");
ThreadDemo demo2 = new ThreadDemo("B");
demo.start();
demo2.start();
}
}
实现Runnable接口
- 定义Runnable接口的实现类并重写run()方法
- 创建实现类的对象,并以此Runnable对象作为Thread的target创建Thread对象,即线程对象
- 调用线程对象的start()方法启动线程
package com.demo.thread;
public class RunnableDemo implements Runnable {
private String name;
public RunnableDemo(String name) {
this.name = name;
}
@Override
public void run() {
int i = 100;
while (i-- > 0) {
System.out.println(String.format("%s:第%d次运行", name, i));
}
}
public static void main(String[] args) {
RunnableDemo demoA = new RunnableDemo("A");
RunnableDemo demoB = new RunnableDemo("B");
new Thread(demoA).start();
new Thread(demoB).start();
}
}
实现Callable接口
- 创建Callable接口的实现类并实现call()方法,该方法具有返回值
- 创建Callable实现类的对象,使用该Callable示例创建FutureTask的对象
- 以FutureTask对象作为Thread的target创建Thread对象,获得线程对象
- 调用线程对象的start()方法启动线程
- 调用FutureTask对象的get()方法获得线程运行结果
package com.demo.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableDemo implements Callable<String> {
private String name;
public CallableDemo(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
int i = 10;
while (i-- > 0) {
System.out.println(String.format("%s:第%d次运行", name, i));
}
return String.format("%s:运行结束", name);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
CallableDemo demoA = new CallableDemo("A");
FutureTask<String> futureTaskA = new FutureTask<>(demoA);
Thread threadA = new Thread(futureTaskA);
CallableDemo demoB = new CallableDemo("B");
FutureTask<String> futureTaskB = new FutureTask<>(demoB);
Thread threadB = new Thread(futureTaskB);
threadA.start();
threadB.start();
System.out.println(futureTaskA.get());
System.out.println(futureTaskB.get());
}
}

本文介绍了Java中创建线程的三种主要方式:继承Thread类、实现Runnable接口和实现Callable接口。每种方式都提供了详细的代码示例,帮助读者理解如何在实际应用中使用这些创建线程的方法。
350

被折叠的 条评论
为什么被折叠?



