JAVA多线程学习(创建线程的方式)

创建线程的方式(在主线程之外创建线程)

1.直接创建线程


//创建需要的线程对象
Thread thread = new Thread(){
//执行的方法
            @Override
            public void run() {
                System.out.println("第一种创建线程的方式");
            }
        };
//启动线程
thread.start();


/****根据lamdba简化代码****/
Thread thread = new Thread(() -> System.out.println("第一种创建线程的方式"));
thread.start();

2.使用Runnable创建线程(Runnable更适合与线程池配合使用,建议使用)


//创建Runnable
Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("第二种创建线程的方式");
            }
        };
        Thread thread = new Thread(runnable);
thread.start();


/****根据lamdba简化代码****/
 Runnable runnable = () -> System.out.println("第二种创建线程的方式");
 Thread thread = new Thread(runnable);
 thread.start();

3.使用FutureTask创建线程


//FutureTask实现了RunnableFuture
public class FutureTask<V> implements RunnableFuture<V>;
//RunnableFuture继承了Runnable和Future
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
//Future的get方法可以返回结果(java的api)
    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

  FutureTask futureTask = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //线程进入阻塞状态
                Thread.sleep(2000);
                System.out.println("第三种创建线程的方式");
                return 20;
            }
        });
//FutureTask实现了Runnable可以把FutureTask直接放在Thread中
Thread thread = new Thread(futureTask);
thread.start();
//futureTask.get();获取线程返回值,如果线程阻塞该方法会等到线程完成后获取结果
log.debug("{}",futureTask.get());

4.用线程池的方式创建线程


Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("第四种创建线程的方式");
            }
        };

//1、创建线程池对象(参数为线程数量)参数(IllegalArgumentException–如果nThreads<=0)
ExecutorService service = Executors.newFixedThreadPool(100);
//2、这里传入的参数是Runnable接口实现类的对象,并调用execute()方法
service.execute(runnable);
//3、关闭线程池
service.shutdown();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值