Java创建线程的方式及实现

Java创建线程的方式及实现

Java创建线程的方式主要有以下三种

  • 继承Thread类
  • 实现Runnable接口
  • 实现Callable接口

继承Thead类

  1. 创建继承自Thread类的子类并重写Thread类的run方法
  2. 通过创建该子类的对象,获得线程对象
  3. 调用线程对象的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接口

  1. 定义Runnable接口的实现类并重写run()方法
  2. 创建实现类的对象,并以此Runnable对象作为Thread的target创建Thread对象,即线程对象
  3. 调用线程对象的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接口

  1. 创建Callable接口的实现类并实现call()方法,该方法具有返回值
  2. 创建Callable实现类的对象,使用该Callable示例创建FutureTask的对象
  3. 以FutureTask对象作为Thread的target创建Thread对象,获得线程对象
  4. 调用线程对象的start()方法启动线程
  5. 调用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 futureTaskA = new FutureTask<>(demoA);
        Thread threadA = new Thread(futureTaskA);
        CallableDemo demoB = new CallableDemo("B");
        FutureTask futureTaskB = new FutureTask<>(demoB);
        Thread threadB = new Thread(futureTaskB);
        threadA.start();
        threadB.start();
        System.out.println(futureTaskA.get());
        System.out.println(futureTaskB.get());
    }

}

你可能感兴趣的:(Java,多线程)