Java创建多线程得8种方式

本文转载自:Java创建多线程的8种方式,并对部分内容进行补充说明。

1、继承Thread类,重写run()方法

//方式1

public class ThreadDemo extends Thread {
    public int a = 1;

    @Override
    public void run() {
        a += 2;
        System.out.println("thread run......:" + a);
    }

    public static void main(String[] args) {
        Thread thread1 = new ThreadDemo();
        Thread thread2 = new ThreadDemo();
        thread1.start();
        thread2.start();

    }
}

2、实现Runnable接口,重写run()

实现Runnable接口只是完成了线程任务的编写
若要启动线程,需要new Thread(Runnable target),再有thread对象调用start()方法启动线程
此处我们只是重写了Runnable接口的Run()方法,并未重写Thread类的run(),让我们看看Thread类run()的实现
本质上也是调用了我们传进去的Runnale target对象的run()方法

//Thread类源码中的run()方法
//target为Thread 成员变量中的 private Runnable target;
 
 @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

所以第二种创建线程的实现代码如下:

/**
 * 第二种创建启动线程的方式
 * 实现Runnale接口
 * @author fatah
 */
public class RunnableDemo implements Runnable {
    int a = 1;

    @Override
    public void run() {
        a += 2;
        System.out.println("test runnable......:" + a);
    }

    public static void main(String[] args) {
        //多个线程共享资源(RunnableDemo中的资源,如a)
        Runnable runnableDemo = new RunnableDemo();
        new Thread(runnableDemo).start();
        new Thread(runnableDemo).start();
        new Thread(runnableDemo).start();

        //不共享资源,每个线程拥有独自的资源
        new Thread(new RunnableDemo()).start();
        new Thread(new RunnableDemo()).start();
        new Thread(new RunnableDemo()).start();

    }
}

实现Runnable接口相比第一种继承Thread类的方式,使用了面向接口,将任务与线程进行分离,有利于解耦

3、匿名内部类的方式

适用于创建启动线程次数较少的环境,书写更加简便
具体代码实现:

package cn.itcats.thread.Test1;
/**
 * 创建启动线程的第三种方式————匿名内部类
 * @author fatah
 */
public class Demo3 {
	public static void main(String[] args) {
		//方式1:相当于继承了Thread类,作为子类重写run()实现
		new Thread() {
			public void run() {
				System.out.println("匿名内部类创建线程方式1...");
			};
		}.start();
		
		
		
		//方式2:实现Runnable,Runnable作为匿名内部类
		new Thread(new Runnable() {
			public void run() {
				System.out.println("匿名内部类创建线程方式2...");
			}
		} ).start();
	}
}

4、带返回值的线程(实现implements Callable<返回值类型>)

以上两种方式,都没有返回值且都无法抛出异常。
Callable和Runnbale一样代表着任务,只是Callable接口中不是run(),而是call()方法,但两者相似,即都表示执行任务,call()方法的返回值类型即为Callable接口的泛型
具体代码实现:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
 
/**
 * 方式4:实现Callable<T> 接口
 * 含返回值且可抛出异常的线程创建启动方式
 * @author fatah
 */
public class CallableDemo implements Callable<String> {
    int a = 1;

    @Override
    public String call() throws Exception {
        a = a + 1;
        //Thread.sleep(2000);
        System.out.println("test callable......:" + a);
        return "callable" + a;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableDemo callableDemo = new CallableDemo();
        /*	call()只是线程任务,对线程任务进行封装
			class FutureTask<V> implements RunnableFuture<V>
			interface RunnableFuture<V> extends Runnable, Future<V>
		*/
        FutureTask<String> task= new FutureTask<>(callableDemo);
        FutureTask<String> task2= new FutureTask<>(callableDemo);
        FutureTask<String> task3= new FutureTask<>(callableDemo);
        new Thread(task).start();
        new Thread(task2).start();
        new Thread(task3).start();
        //get()获取线程执行结果
        System.out.println("执行结果:" + task.get());
        System.out.println("执行结果:" + task2.get());
        System.out.println("执行结果:" + task3.get());
    }
}

4.1、Runnable 和Callable的区别

  • Runnable没有返回值,调用者不能获取线程执行结果;Callable 有返回值,调用者可以获取线程执行结果。
  • Runnable不能抛出异常,因为run()方法就没有抛出异常的声明,所以无法抛出异常,异常只能run()方法内部处理,无法抛给调用者,调用者捕获不到线程内部异常。Callable可以抛出异常,可以将call()中异常抛出给调用者处理,调用者可以捕获到线程异常。
    查看Runnable源码可以看到run()方法无返回值,没有throws Exception声明:
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

查看Callable源码可以看到call()方法有返回值,有throws Exception声明:

 @FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

4.2、Runnable 和Callable的区别实例

Runnable run()方法中指定异常,并在catch中抛出:

public class RunnableDemo implements Runnable {
    int a = 0;

    @Override
    public void run(){
        a += 1;
        try {
            System.out.println("test runnable......:");
            int b = a / 0;
        } catch (Exception e) {
            System.out.println("线程中run方法异常。。。111");
            throw new RuntimeException("抛出线程中run方法异常。。。222");
        }
    }

    public static void main(String[] args) {
        try {
            Runnable runnableDemo = new RunnableDemo();
            new Thread(runnableDemo).start();
        } catch (Exception e) {
            System.out.println("捕获线程中run方法异常。。。333");
            System.out.println(e.getMessage());
        }
        System.out.println("over....");
    }
}

执行结果如下:

over....
test runnable......:
线程中run方法异常。。。111
Exception in thread "Thread-0" java.lang.RuntimeException: 抛出线程中run方法异常。。。222
	at com.vpcteleservice.ipLight.test.RunnableDemo.run(RunnableDemo.java:18)
	at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 0

从执行结果可以看出调用者无法捕获异常,因为run()方法根本抛不出。

CallableDemo call()方法中指定异常,并在catch中抛出:

public class CallableDemo implements Callable<String> {
    int a = 1;
    @Override
    public String call() throws Exception {
        try {
            a=a+1;
            //Thread.sleep(2000);
            System.out.println("test callable......:");
            int b = a/0;
            return "success";
        }catch (Exception e){
            System.out.println("Callable中call方法异常111");
            throw new RuntimeException("抛出Callable中call方法异常222");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        try {
            CallableDemo callableDemo = new CallableDemo();
            FutureTask<String> future = new FutureTask<>(callableDemo);
            new Thread(future).start();
            System.out.println(future.get());
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println("捕获Callable中call方法异常333");
        }
        System.out.println("over");
    }
}

执行结果如下:

test callable......:
Callable中call方法异常111
java.lang.RuntimeException: 抛出Callable中call方法异常222
捕获Callable中call方法异常333
over

Process finished with exit code 0

从执行结果中可以看出线程抛出异常,调用者能捕获到。

5、定时器(java.util.Timer)

关于Timmer的几个构造方法

执行定时器任务使用的是schedule方法:

具体代码实现:

import java.util.Timer;
import java.util.TimerTask;
 
/**
 * 方法5:创建启动线程之Timer定时任务
 * @author fatah
 */
public class Demo6 {
	public static void main(String[] args) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("定时任务延迟0(即立刻执行),每隔1000ms执行一次");
			}
		}, 0, 1000);
	}
	
}

我们发现Timer有不可控的缺点,当任务未执行完毕或我们每次想执行不同任务时候,实现起来比较麻烦。这里推荐一个比较优秀的开源作业调度框架“quartz”,在后期我可能会写一篇关于quartz的博文。

6、线程池的实现(java.util.concurrent.Executor接口)

降低了创建线程和销毁线程时间开销和资源浪费
具体代码实现:

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
 
public class Demo7 {
	public static void main(String[] args) {
		//创建带有5个线程的线程池
		//返回的实际上是ExecutorService,而ExecutorService是Executor的子接口
		Executor threadPool = Executors.newFixedThreadPool(5);
		for(int i = 0 ;i < 10 ; i++) {
			threadPool.execute(new Runnable() {
				public void run() {
					System.out.println(Thread.currentThread().getName()+" is running");
				}
			});
		}
	}
}

运行结果:

pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-3 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-5 is running
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running

运行完毕,但程序并未停止,原因是线程池并未销毁,若想销毁调用threadPool.shutdown(); 注意需要把我上面的
Executor threadPool = Executors.newFixedThreadPool(10); 改为
ExecutorService threadPool = Executors.newFixedThreadPool(10); 否则无shutdown()方法

若创建的是CachedThreadPool则不需要指定线程数量,线程数量多少取决于线程任务,不够用则创建线程,够用则回收。

7、Lambda表达式的实现(parallelStream)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * 使用Lambda表达式并行计算
 * parallelStream
 * @author fatah
 */
public class Demo8 {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(1,2,3,4,5,6);
		Demo8 demo = new Demo8();
		int result = demo.add(list);
		System.out.println("计算后的结果为"+result);
	}
	
	public int add(List<Integer> list) {
		//若Lambda是串行执行,则应顺序打印
		list.parallelStream().forEach(System.out :: println);
		//Lambda有stream和parallelSteam(并行)
		return list.parallelStream().mapToInt(i -> i).sum();
	}
}

运行结果:

4
1
3
5
6
2

计算后的结果为21
事实证明是并行执行

8、Spring实现多线程

(1)新建Maven工程导入spring相关依赖
(2)新建一个java配置类(注意需要开启@EnableAsync注解——支持异步任务)

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
 
@Configuration
@ComponentScan("com.test.thread")
@EnableAsync
public class ThreadAsyncConfig implements AsyncConfigurer{
	@Bean(name = "asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(10);
        //设置最大线程数
        threadPool.setMaxPoolSize(100);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        //  线程名称前缀
        threadPool.setThreadNamePrefix("myAsync-");
        //线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy
        //AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
        //CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
        //DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
        //DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }
}

(3)书写异步执行的方法类(注意方法上需要有@Async——异步方法调用)

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
 
@Service
public class AsyncService {
	
	@Async
	public void Async_A() {
		System.out.println("Async_A is running");
	}
	
	@Async
	public void Async_B() {
		System.out.println("Async_B is running");
	}
}

(4)创建运行类

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 public class Run {
	public static void main(String[] args) {
		//构造方法传递Java配置类Config.class
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
		AsyncService bean = ac.getBean(AsyncService.class);
		bean.Async_A();
		bean.Async_B();
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值