多线程的实现方式
继承Thread类的方式
- 创建一个继承于Thread类的子类
- 重写Thread类的run() --将执行的操作声明在run()中
- 创建Thread类的子类的对象
- 通过此对象调用start():
class Thread1 extends Thread{
@Override
public void run() {
for (int i =0;i<100;i++){
if (i % 2 == 0 ) {
System.out.println(i);
}
}
}
}
public class ThreadTest{
public static void main(String[] args) {
Thread1 t1 = new Thread1();
t1.start();
}
}
Thread类的相关方法
- start():调用当前线程的run()
- run():重写此方法,将要进行的操作声明在此方法中
- currentTread():静态方法,返回当前线程
- getName():获取当前线程名
- setName():设置当前线程名
- yield():释放当前cpu执行权
- join():在a线程中调用b的join(),a会阻塞,直到b执行完,线程a才结束阻塞状态
- stop():停止 过时
- sleep(long millis):睡眠
实现Runnable接口的方式
- 创建一个实现Runnable接口的类
- 实现类去实现Runnable中的抽象方法:run()
- 创建实现类对象
- 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
- 通过Thread类的对象调用start()
实现Callable接口
- 创建一个类实现Callable接口
- 创建实现类对象
- 创建FutureTask封装异步任务
- 把FutureTask对象交给Thread对象执行
- 线程执行后可以通过FutureTask的get()方法获取方法call()的返回对象
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable ct = new CallableTest();
FutureTask ft = new FutureTask(ct);
Thread t = new Thread(ft);
t.start();
Example e = (Example)ft.get();
System.out.println(e);
}
}
class CallableTest implements Callable{
@Override
public Example call() throws Exception {
return new Example("例子",55);
}
}
class Example{
String name;
Integer amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Example(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
@Override
public String toString() {
return "Example{" +
"name='" + name + '\'' +
", amount=" + amount +
'}';
}
}
使用线程池
- 通过Executors(异步执行框架)的类方法创建一个制定线程大小的线程池
- 定义一个线程对象,若要返回值则实现Callable接口
- 可以使用线程池对象的submit()方法获取异步任务对象
- 通过异步任务的get()方法获取线程中的返回值
public class ThreadTest1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<>();
for (int i = 0;i<taskSize;i++) {
Callable ct = new CallableTest1();
Future future = pool.submit(ct);
list.add(future);
}
pool.shutdown();
for (Future f : list) {
System.out.println(">>>" + f.get().toString());
}
}
}
class CallableTest1 implements Callable{
@Override
public Example1 call() throws Exception {
return new Example1("例子",55);
}
}
class Example1{
String name;
Integer amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Example1(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
@Override
public String toString() {
return "Example{" +
"name='" + name + '\'' +
", amount=" + amount +
'}';
}
}