欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

线程创建的三种方式

程序员文章站 2022-07-10 17:28:47
线程创建的三种方式一、继承Thread类/**public class Threadextends Objectimplements Runnable*///继承Thread类public class MyThread extends Thread{//重写run()方法 public void run(){ for(int i = 1; i<=100; i++){ System.out.println("i: "+i);...

线程创建的三种方式

一、继承Thread类

/**
public class Thread
extends Object
implements Runnable
*/
//继承Thread类
public class MyThread extends Thread{
	//重写run()方法
    public void run(){
        for(int i = 1; i<=100; i++){
            System.out.println("i: "+i);
        }
    }
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        MyThread myThread2 = new MyThread();
		//调用start()方法开启多线程执行
        myThread.start();
        myThread2.start();
    }
}

二、实现Runnable接口

因为Java是单继承,所以推荐使用Runnable接口

//实现Runnable接口
public class MyThread implements Runnable{
	//重写run()方法
    public void run(){
        for(int i = 1; i<=100; i++){
            System.out.println("i: "+i);
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        MyThread myThread2 = new MyThread();
        //创建线程对象(Thread)调用构造器,将MyThread 对象实例传入并调用start()方法
        new Thread(myThread).start();
        new Thread(myThread2).start();
    }
}

三、实现Callable接口

与使用Runnable相比,Callable功能更加强大

  1. 相比run()方法,可以有返回值
  2. 方法可以抛出异常
  3. 支持泛型的返回值
  4. 需要借助FutureTask类,比如获取返回值结果
package com.hui.springcloudyang.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        synchronized (this) {
            int ticket = 0;
            for (int i = 0; i < 1000; i++) {
                ticket++;
                System.out.println(Thread.currentThread().getName() + "当前票数为:" + ticket);
            }
            return ticket;
        }
    }

    public static void main(String[] args) {
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask(myCallable);
        new Thread(futureTask,"线程1").start();


        try {
            Integer ticket = futureTask.get();
            System.out.println(ticket);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

本文地址:https://blog.csdn.net/weixin_44362355/article/details/110700900

相关标签: Java基础