1. 继承Thread类
通过继承Thread类,并重写它的run方法,就可以创建一个线程。
public class TestThread1 extends Thread {
public TestThread1(String name) {
super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":Hello!");
}
public static void main(String[] args) {
TestThread1 bob = new TestThread1("Bob");
TestThread1 alice = new TestThread1("Alice");
bob.start();
alice.start();
}
}
- 首先定义一个类来继承Thread类,重写run方法。
- 然后创建这个子类对象,并调用start方法启动线程。
执行结果:
2. 实现Runnable接口
通过实现Runnable ,并实现run方法
public class TestThread2 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":Hello!");
}
public static void main(String[] args) {
TestThread2 testThread = new TestThread2();
new Thread(testThread, "Bob").start();
new Thread(testThread, "Alice").start();
}
}
- 首先定义一个类实现 Runnable接口,并实现run方法。
- 然后创建Runnable实现类对象,并把它作为target传入Thread的构造函数中
- 最后调用start方法启动线程。
执行结果:
3.使用Callable和FutureTask创建多线程
使用Callable和FutureTask创建线程的步骤如下:
- 创建一个Callable接口的实现类,并实现其call()方法,编写异步执行的具体逻辑,可以有返回值
- 使用Callable实现类的实例构造一个FutureTask实例
- 使用FutrueTask实例作为Thread构造器的target入参,构造新的Thread线程实例
- 调用Thread实例的start()方法启动线程,启动新线程的run()方法并发执行
- 调用FutureTask对象的get()方法阻塞性地获取并发线程执行结果
import java.util.concurrent.*;
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
SingleCallable singleCallable = new SingleCallable();
SingleCallable singleCallable1 = new SingleCallable();
singleCallable1.flag = -1;
FutureTask futureTask = new FutureTask(singleCallable);
FutureTask futureTask1 = new FutureTask(singleCallable1);
new Thread(futureTask).start();
new Thread(futureTask1).start();
System.err.println(futureTask.get());
System.err.println(futureTask1.get());
}
}
class SingleCallable implements Callable<Boolean> {
int flag = 0;
@Override
public Boolean call() throws Exception {
if (flag >= 0) {
return true;
} else {
return false;
}
}
}
区别
Runnable的唯一抽象方法run()没有返回值,也没受检查异常的异常声明,Callable接口的call()有返回值,并且声明了受检查异常,功能更强
4. 线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.execute(new Thread(new SingleThread()));
executorService.execute(new Thread(new SingleThread()));
executorService.execute(new Thread(new SingleThread()));
executorService.shutdown();
}
}
class SingleThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
java
标签:JAVA,Thread,创建,start,run,线程,new,public
From: https://www.cnblogs.com/wwwgo/p/17352668.html