JavaSE-多线程

本文介绍了Java中创建线程的三种方式,包括继承Thread类、实现Runnable接口和Callable接口,并详细讨论了线程同步的三种方法(同步代码块、同步方法和Lock锁),以及如何使用线程池管理和优化并发任务。此外,还对比了悲观锁和乐观锁的使用场景。
摘要由CSDN通过智能技术生成

1.创建线程

创建线程有三种方式,都需要子类,然后在主程序中使用它。

其一

继承Thread类,重写run方法,这种方式简单,但是没法继承其他类

public class Test01_01 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            logger.info("thread sout:"+i);
        }
    }
}

运行方式如下

Thread t = new Test01_01();
t.start();
其二

实现Runnable接口,重写run方法,这种方式避免了无法继承别的类的缺陷

public class Test02_01 implements Runnable{
    @Override
    public void run() {
        Thread cut = Thread.currentThread();
        for (int i = 0; i < 5; i++) {
            System.out.println("thread ["+cut.getName()+"]"+i);
        }
    }
}

运行方式如下

Runnable target = new Test02_01();
new Thread(target).start();

或者使用lambda表达式

new Thread(()->{
    Thread cut = Thread.currentThread();
        for (int i = 0; i < 5; i++) {
            System.out.println("thread ["+cut.getName()+"]"+i);
        }
    }).start();
其三

实现Callable接口,重写call方法,这种方式可以取得线程的返回值

    private static class Test04_01 implements Callable<Long>{
        @Override
        public Long call() throws Exception {
            Thread cut = Thread.currentThread();
            System.out.println("当前线程:"+cut.getName());
            long res = 0;
            for (int i = 0; i < 100; i++) {
                for (int j = 0; j < 100; j++) {
                    res += j;
                }
            }
            return res;
        }
    };

运行方式如下

        Callable<Long> call = new Test04_01();
        FutureTask<Long> task = new FutureTask<>(call);
        new Thread(task).start();
        Long l = task.get();
        System.out.println(l);

2.线程常用方式

在这里插入图片描述

3.线程同步

三种办法

其一

同步代码块,在类中使用

synchronized (LockObject){
	//your code
}

对于示例方法,使用this作为LockObject,
对于静态方法,使用类名.class作为LockObject

其二

同步方法,在方法前加上synchronized 关键字
同步方法其实底层也是有隐式锁对象的,只是锁的范围是整个方法代码。
如果方法是实例方法:同步方法默认用this作为的锁对象。
如果方法是静态方法:同步方法默认用类名.class作为的锁对象。

其三

Lock锁,定义一把锁,需要加锁时lock,结束时unlock,

private final Lock lk = new ReentrantLock();
try {
       lk.lock();
       money -= 1;
     } catch (Exception e) {
         throw new RuntimeException(e);
     } finally {
         lk.unlock();
     }

4.线程池

创建线程的开销是很大的。使用线程池可以复用线程,迭代任务不迭代线程,这样意味着,我们只能只用Runnable和Callable的方式开多线程。

创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 5, 8, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

七个参数的意思分别是:

  1. 核心线程数(一直存活的线程数)
  2. 最大线程数(最大-核心=允许存在的临时线程数)
  3. 临时线程存活时间(如果临时线程超过这个时间没有被分配任务就消亡)
  4. 存活时间单位
  5. 等待队列(ArrayBlockingQueue对象,需指定长度,被线程拿走的任务不算在等待队列)
  6. 线程工厂(使用Executors工具类即可)
  7. 拒绝策略(线程都在忙,等待队列满了,新的任务怎么处理)

临时线程的开启条件为,一个新任务来了,核心线程都在忙,同时等待队列已满,同时线程数还没达到最大线程数时,临时线程被创建,拿走新任务。

线程池常用方法

在这里插入图片描述
执行Runnable任务如下

Runnable target1 = new MyRunnable();
threadPool.execute(target1);// core 1

执行Callable任务如下

Callable<Integer> callableTask = new MyCallable();
Future<Integer> future = threadPool.submit(callableTask);
拒绝策略

在这里插入图片描述

线程池工具类

在这里插入图片描述
这样就不用自己去设计ThreadPoolExecutor了,Executors底层是封装ThreadPoolExecutor的。

一个经验之谈
计算密集型任务:核心线程数量=CPU核数 + 1
IO密集型任务:核心线程数量=CPU核数 * 2

在这里插入图片描述

5.并行并发

并发并行
CPU能同时处理线程的数量有限,为了保证全部线程都能往前执行,CPU会轮巡为系统的每个线程服务,由于CPU切换的速度很快,给我们的感觉这些线程在同时执行,这就是并发。在同一个时刻上,同时有多个线程在被CPU调度执行。

多线程是并发和并行同时进行的!
在这里插入图片描述

6.悲观乐观锁

悲观锁乐观锁
一上来就加锁,没有安全感。每次只能一个线程进入访问完毕后,再解锁。线程安全,性能较差!一开始不上锁,认为是没有问题的,大家一起跑,等要出现线程安全问题的时候才开始控制。线程安全,性能较好。

上述三种线程同步默认都是悲观锁。以下是一个悲观锁和乐观锁比较代码

public class PostLock01 {
    private static class MyRunnable01 implements Runnable{
        private int number;
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                synchronized (this){
                    ++number;
                }
            }
        }
    };
    private static class MyRunnable02 implements Runnable{
//        private int number;
        private AtomicInteger number = new AtomicInteger();
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                number.incrementAndGet();
            }
        }
    };

    public static void main(String[] args) {
        long timeStart, timeEnd;
        timeStart = System.currentTimeMillis();
        pessLock();
        timeEnd = System.currentTimeMillis();
        System.out.println("pessimism : "+(timeEnd - timeStart)+" ms");

        timeStart = System.currentTimeMillis();
        optiLock();
        timeEnd = System.currentTimeMillis();
        System.out.println("optimism : "+(timeEnd - timeStart)+" ms");
    }

    public static void pessLock(){
        Runnable target = new MyRunnable01();
        for (int i = 0; i < 32; i++) {
            new Thread(target).start();
        }
    }

    public static void optiLock(){
        Runnable target = new MyRunnable02();
        for (int i = 0; i < 32; i++) {
            new Thread(target).start();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值