Java线程的创建

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

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

继承Thread类

实现步骤

  1. 自定义线程类继承Thread类
  2. 重写run()方法,编写线程执行体,是线程的入口函数
  3. 创建线程对象,调用start()方法启动线程
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//线程开启不一定立即执行,由CPU调度执行
public class TestThread extends Thread{
    public void run(){
        for (int i = 0; i < 20000; i++) {
            System.out.println("另外的线程"+ i);
        }
    }

    public static void main(String[] args) {
        TestThread thread = new TestThread();
        thread.start();
        for (int i = 0; i < 20000; i++) {
            System.out.println("主线程"+i);
        }
    }
}

实现Runnable接口

实现步骤

  1. 定义MyRunnable类实现Runnable接口
  2. 实现run()方法,编写线程执行体,即入口函数
  3. 创建线程对象,调用start()函数启动线程
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入
//runnable接口实现类,调用start方法
public class TestThread1 implements Runnable {
    public void run(){
        for (int i = 0; i < 20000; i++) {
            System.out.println("另外的线程"+ i);
        }
    }

    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread1 thread1 = new TestThread1();
        //创建线程对象,通过线程对象来开启线程,代理
        Thread thread = new Thread(thread1);
        thread.start();
        for (int i = 0; i < 20000; i++) {
            System.out.println("主线程"+i);
        }
    }
}

实现Callable接口

  1. 实现Callable就扣,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务 ExecutorService ser = Executors.newFixedThreadPool(线程数)
  5. 提交执行 Future r1 = ser.submit(thread1);
  6. 获取结果 boolean res1 = r1.get();
  7. 关闭服务 ser.shutdownNow();
package MultiProcess;

import com.sun.org.apache.xpath.internal.operations.Bool;

import java.util.concurrent.*;

public class TestThread2 implements Callable<Boolean> {

    public Boolean call(){
        for (int i = 0; i < 20000; i++) {
            System.out.println(Thread.currentThread().getId());
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestThread2 thread1 = new TestThread2();
        TestThread2 thread2 = new TestThread2();
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(2);
        //提交执行
        Future<Boolean> r1 = ser.submit(thread1);
        Future<Boolean> r2 = ser.submit(thread2);
        //获取结果
        boolean res1 = r1.get();
        boolean res2 = r2.get();
        //关闭服务
        ser.shutdownNow();
    }
}
posted @ 2020-10-15 20:15  提笔书几行  阅读(89)  评论(0编辑  收藏  举报