多线程的四种创建方式

方式1:
>继承于Thread类
> 创建一个继承于Thead类的子类
>重写Thread类的run方法
>创建Thread的对象
>通过该对象调用start()

class A extends Thread{
    @Override
    public void run() {
        for (int i= 1 ;i<=100; i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName()+" : "+i);
            }
        }
    }
}
//在main方法中直接调用start()方法;
public static void main(String[] args) {

	A a = new A();
	a.start();
}

方式2:
>创建一个实现类实现Runnable的接口
>实现类实现Runnable的run()方法
>创建实现类的对象
>将该对象作为参数放到Thread的构造器中创建Thead对象
>通过Thread类的对象调用start()方法;

class B implements  Runnable{

    @Override
    public void run() {
        for (int i= 1 ;i<=100; i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName()+" : "+i);
            }
        }
    }
}

//先要创建实现类的对象,然后把该对象放进Thead()的构造器中,再调用start()方法
public static void main(String[] args) {
 	B b = new B();
 	Thread thread = new Thread(b);
	thread.start();
 }

方式3:
>实现Callable接口
>实现call方法,将线程要执行的操作声明在call方法中
>创建Callable接口实现类的对象
>将此Callable接口实现了的对象作为参数传到FutureTask构造器中,创建FutureTask的对象
>将FutureTask的对象放到Thread的构造器中并调用start方法

class C implements Callable{

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i= 1 ;i<=100; i++){
            sum += i;
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName()+" : "+i);
            }
        }
        return sum;
    }
}
//先要创建实现类的对象,然后将该对象放到FutureTask的构造器中生成FutureTask的对象,再将这个对象放到Thread的构造器中再调用start()方法
public static void main(String[] args) {
	C c = new C();
	FutureTask task = new FutureTask(c);
	Thread thread1 = new Thread(task);
	thread1.start();
	try {
	    Object o = task.get();
	    System.out.println(o+"***********************");
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} catch (ExecutionException e) {
	    e.printStackTrace();
	}

}

方式4:线程池
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁,实现重复利用。
好处:
一、提高响应效率
二、降低资源消耗
三、便于线程管理

public static void main(String[] args) {
	ExecutorService executorService = Executors.newFixedThreadPool(10);
	executorService.execute(new B());//适用于实现Runnable接口的
	executorService.execute(new A());//也适用于继承Thread类的
	
	executorService.submit(new B());//适用于实现Runnable接口的
	executorService.submit(new C());//适用于实现Callable接口的
}

方式二和方式三的区别:
实现Callable接口比实现Runnable接口创建的功能更加强大
一、相比run()方法,Callable的call方法可以带有返回值,需要借助FutureTask类,获取返回结果。
二、可以抛出异常,方便捕获错误
三、支持泛型

希望该文章对你们有帮助哈,有帮到你们的麻烦点个赞哈,有兴趣的朋友可以关注一下公众号,公众号上会发布一些最近行业常用的技术,还有一些自己见解的文章。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fighting32/article/details/107022646