Java多线程与并发

进程和线程的区别

进程和线程的由来

  • 串行 初期的计算机智能串行执行任务,并且需要长时间等待用户输入.
  • 批处理 预告将用户的指令集中成清单,指量串行处理用户指令,仍然无法并发执行.
  • 进程 进程独占内存空间,保存各自运行状态,相互间不干扰且可以互相切换,为并发处理任务提供了可能.
  • 线程 共享进程的内存资源,相互间切换更快速,支持更细粒度的任务控制,使进程内的子任务得以并发执行
    进程是资源分配的最小单位,线程是CPU调度的最小单位
  • 所有与进程相关的资源,都被记录在PCB中
    在这里插入图片描述
  • 进程是抢占处理机的调度单位;线程属于某个进程,共享其资源.
  • 线程只由堆栈寄存器,程序计数器和TCB组成.
    在这里插入图片描述
    总结
  • 线程不能看做独立应用,而进程可看做独立应用
  • 进程有独立的地址空间,互相不影响,线程只是进程的不同执行路径
  • 线程没有独立的地址空间,多进程的程序比多线程程序健壮
  • 进程的切换比线程的切换开销大

Java进程和线程的关系

  • Java对操作系统提供的功能进行了封闭,包括进程和线程
  • 运行一个程序会产生一个进程,进程包含至少一个线程
  • 每个进程对应一个JVM实例,多个线程共享JVM里的堆
  • Java采用单线程编程模型,程序会自动创建主线程
  • 主线程可以创建子线程,原则上要后于子线程完成执行

Thread中的start和run方法的区别

  • 调用start()方法会创建一个新的子线程并启动
  • run()方法只是Thread的一个普通方法的调用.

Thread和Runnable是什么关系

  • Thread是实现了Runnable接口的类,使得run支持多线程
  • 因类的单一继承原则,推荐多使用Runnable接口

如何实现处理线程的返回值

  • 主线程等待法
package thread;

public class CycleWait implements Runnable {
    private String value;

    @Override
    public void run() {
        try {
            Thread.currentThread().sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = "we have data now";
    }

    public static void main(String[] args) throws InterruptedException {
        CycleWait cw = new CycleWait();
        Thread t1 = new Thread(cw);
        t1.start();
        while(cw.value==null){
            System.out.println("sleep...");
            Thread.currentThread().sleep(1000);
        }
        System.out.println("value:"+cw.value);
    }

}
  • 使用Thread类的join()阻塞当前线程以等待子线程处理完毕
        t1.join();
//        while(cw.value==null){
//            System.out.println("sleep...");
//            Thread.currentThread().sleep(1000);
//        }
  • 使用Callable接口实现:通过FutureTask Or 线程池获取
package thread.mycallable;

import java.util.concurrent.Callable;

public class Mycallable implements Callable<String> {
   @Override
   public String call() throws Exception {
       String value="test";
       System.out.println("ready to work");
       Thread.currentThread().sleep(3000);
       System.out.println("task done");
       return value;
   }
}
package thread.mycallable;

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

public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> task=new FutureTask<String>(new Mycallable());
        new Thread(task ).start();
        if(!task.isDone()){
            System.out.println("task has not finished,please wait!");
        }
        System.out.println("task return:"+task.get());
    }
}
package thread.mycallable;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        Future<String> future = newCachedThreadPool.submit(new Mycallable());
        if (!future.isDone()){
            System.out.println("task has not finished,please wait!");
        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            newCachedThreadPool.shutdown();
        }
    }
}

如何给run()方法传参

  • 构造函数传参
  • 成员变量传参
  • 回调函数传毵

线程的状态

  • new新建,创建后尚未启动的线程的状态
  • Runnable,包含Running和Ready
  • Waiting无限期等待,不会被分配CPU执行时间,需要显式被唤醒
    没有设置Timeout参数的Object.wait()方法.
    没有设置Timeout参数的Thread.join()方法.
    LockSupport.park()方法.
  • Timed Waiting限期等待,在一定时间后会由系统自动唤醒.
    Thread.sleep()方法.
    设置了Timeout参数的Object.wait()方法.
    设置了Timeout参数的Thread.join()方法.
    LockSupport.parkNanos()方法.
    LockSupport.parkUntil()方法.
    -Blocked阻塞,等待获取排它锁.
    -Terminated,结束,已终止线程的状态,线程已经结束执行.

sleep和wait的区别

基本的差别

  • sleep是Thread类的方法,wait是Object类中定义的方法
  • sleep方法可以在任何地方使用.wait方法只能在synchronized方法或者synchronized块中使用
    最主要的本质区别
  • Thread.sleep只会让出CPU,不会导致锁行为的改变
  • Object.wait不仅让出CPU,还会释放已经占用的同步资源锁.

notify和notifyall

  • 锁池EntryList
    假设线程A已经拥有了某个对象(不是类)的锁,而其它线程B,C想要调用这个对象的某个synchronized方法(或块),由于B,C线程在进入对象的synchronized方法或块之前必须先获取该对象锁的拥有权,而恰巧该对象的锁目前正被线程A所占用,此时B,C线程就会被阻塞,进入一个地方支等等锁的释放,这个地方便是该对象的锁池.

  • 等待池WaitSet
    假设线程A调用了某个对象的wait()方法,线程A就会释放该对象的锁,同时线程A就进入到了该对象的等待池中,进入到等等池中的线程不会去竞争该对象的锁.

  • notifyAll会让所有处于等待池的线程全部进入锁池去竞争获取锁的机会

  • notify只会随机选取一个处于等待池中的线程进入锁池支竞争获取锁的机会

yield

当调用Thread.yield()函数时,会给线程调度器一个当前线程愿意让出CPU使用的提示,但是线程调度器可能会忽略这个暗示.
yield不影响锁的状态

interrupt函数

已经被抛弃的方法

  • 通过调用stop()方法停止线程.
  • 调用suspend()和resume()方法
    目前使用的方法
  • 调用interrupt(),通知线程应该中断了.
  1. 如果线程处于被阻塞状态,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常.
  2. 如果线程处于正常活动状态,那么会将该线程的中断标志设置为true.被设置中断标志的线程将继续正常运行,不受影响.
  • 需要被调用的线程配合中断
  1. 在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程.
  2. 如果线程牌正常活动状态,那么会将该线程的中断标志设置为true.被设置中断标志继续正常运行,不受影响.

synchronized

线程安全问题的主要诱因

  • 存在共享数据(也称临界资源)
  • 存在多条线程共同操作这些共享数据
    解决问题的根本方法:
    同一时刻有且只有一个线程在操作共享数据,其他线程必须等到该线程处理完数据后再对共享数据进行操作.

互斥锁的特性
互斥性,即在同一时间只允许一个线程持有某个对象锁,通过这种特性来实现 多线程的协调机制,这样在同一时间只有一个线程对需要同步的代码块(复合操作)进行访问.互斥性也称为操作的原子性
可见性,必须确保在锁被释放之前,对共享变量所做的修改,对于随后获得该锁的另一个对象是可见的(即在获得应获得最新共享变量的值),否则另一个线程可能是在本地缓存的某个副本上继续操作,从而引起不一致.

synchronized锁的不是代码,锁的都是对象.

根据获取的锁的分类:获取对象锁和获取类锁
获取对象两种用法

  • 同步代码块(synchronized(this),synchronized(类的实例对象)),锁是小括号中的实例对象.
  • 同步非静态方法(synchronized method),锁的是当前对象的实例对象.

获取类两种方法

  • 同步代码块(synchronized(类.class)),锁的是小括号中的类对象(Class对象)
  • 同步静态方法(synchronized static method)锁是当前对象的类对象(Class对象)

对象锁和类锁的总结

  1. 有线程访问对象的同步代码块时,另外的线程可以访问该对象的非同步代码块
  2. 若锁住的是同一个对象,一个线程在访问对象的同步代码块时,另一个访问对象的同步代码块的线程会被阻塞.
  3. 若锁住的是同一个对象,一个线程在访问对象的同步方法时,另一个访问对象的同步方法的线程会被阻塞
  4. 若锁隹的是同一个对象,一个线程在访问对象的同步代码块时,另一个访问对象同步方法的线程会被阻塞,反之亦然.
  5. 同一个类的不同对象的对象锁互不干扰
  6. 类锁由于也是一种特殊的对象锁,因此表现和上述一致,而由于一个类只有一把对象锁,所以同一个类的不同对象使用类锁将会是同步的;
  7. 类锁和对象锁互不干扰.

Java线程池

利用Executors创建不同的线程池满足不同场景的需求
在这里插入图片描述
在这里插入图片描述

为什么要使用线程池

  • 降低资源消耗
  • 提高线程的可管理性
    在这里插入图片描述

J.U.C的三个Executor接口 (java.util.concurrent)

  • Exector:去年新任务的简单接口,将任务提交和任务执行细节解耦
    在这里插入图片描述
  • ExecutorService:具备管理执行器和任务生命周期的方法,提交任务机制更完善
  • ScheduledExecutorService:支持Future和定期执行任务.

ThreadPoolExecutors构造函数

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */
     /*
    * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * /
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值