这一组是 Object 类的方法 须要注意的是:这三个方法都必须在同步的范围内调用html
wait 阻塞当前线程,直到 notify 或者 notifyAll 来唤醒java
wait有三种方式的调用
wait()
必要要由 notify 或者 notifyAll 来唤醒
wait(long timeout)
在指定时间内,若是没有notify或notifAll方法的唤醒,也会自动唤醒。
wait(long timeout,long nanos)
本质上仍是调用一个参数的方法
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
复制代码
这一组是 Thread 类的方法面试
sleep 让当前线程暂停指定时间,只是让出CPU的使用权,并不释放锁编程
yield 暂停当前线程的执行,也就是当前CPU的使用权,让其余线程有机会执行,不能指定时间。会让当前线程从运行状态转变为就绪状态,此方法在生产环境中不多会使用到,官方在其注释中也有相关的说明缓存
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
复制代码
join 等待调用 join 方法的线程执行结束,才执行后面的代码 其调用必定要在 start 方法以后(看源码可知) 使用场景:当父线程须要等待子线程执行结束才执行后面内容或者须要某个子线程的执行结果会用到 join 方法多线程
java编程语言容许线程访问共享变量,为了确保共享变量能被准确和一致的更新,线程应该确保经过排他锁单独得到这个变量。Java语言提供了volatile,在某些状况下比锁更加方便。若是一个字段被声明成volatile,java线程内存模型确保全部线程看到这个变量的值是一致的。并发
valitate是轻量级的synchronized,不会引发线程上下文的切换和调度,执行开销更小。app
内存可见性 多线程操做的时候,一个线程修改了一个变量的值 ,其余线程能当即看到修改后的值异步
防止重排序 即程序的执行顺序按照代码的顺序执行(处理器为了提升代码的执行效率可能会对代码进行重排序)编程语言
并不能保证操做的原子性(好比下面这段代码的执行结果必定不是100000)
public class testValitate {
public volatile int inc = 0;
public void increase() {
inc = inc + 1;
}
public static void main(String[] args) {
final testValitate test = new testValitate();
for (int i = 0; i < 100; i++) {
new Thread() {
public void run() {
for (int j = 0; j < 1000; j++)
test.increase();
}
}.start();
}
while (Thread.activeCount() > 2) { //保证前面的线程都执行完
Thread.yield();
}
System.out.println(test.inc);
}
}
复制代码
确保线程互斥的访问同步代码
synchronized 是JVM实现的一种锁,其中锁的获取和释放分别是 monitorenter 和 monitorexit 指令,该锁在实现上分为了偏向锁、轻量级锁和重量级锁,其中偏向锁在 java1.6 是默认开启的,轻量级锁在多线程竞争的状况下会膨胀成重量级锁,有关锁的数据都保存在对象头中
加了 synchronized 关键字的代码段,生成的字节码文件会多出 monitorenter 和 monitorexit 两条指令(利用javap -verbose 字节码文件可看到关,关于这两条指令的文档以下:
monitorenter Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows: • If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor. • If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count. • If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.
monitorexit The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref. The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.
加了 synchronized 关键字的方法,生成的字节码文件中会多一个 ACC_SYNCHRONIZED 标志位,当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,若是设置了,执行线程将先获取monitor,获取成功以后才能执行方法体,方法执行完后再释放monitor。在方法执行期间,其余任何线程都没法再得到同一个monitor对象。 其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需经过字节码来完成。
会让没有获得锁的资源进入Block状态,争夺到资源以后又转为Running状态,这个过程涉及到操做系统用户模式和内核模式的切换,代价比较高。Java1.6为 synchronized 作了优化,增长了从偏向锁到轻量级锁再到重量级锁的过分,可是在最终转变为重量级锁以后,性能仍然较低。
AtomicBoolean,AtomicInteger,AtomicLong以及 Lock 相关类等底层就是用 CAS实现的,在必定程度上性能比 synchronized 更高。
CAS全称是Compare And Swap,即比较替换,是实现并发应用到的一种技术。操做包含三个操做数 —— 内存位置(V)、预期原值(A)和新值(B)。 若是内存位置的值与预期原值相匹配,那么处理器会自动将该位置值更新为新值 。不然,处理器不作任何操做。
若是只是用 synchronized 来保证同步会存在如下问题 synchronized 是一种悲观锁,在使用上会形成必定的性能问题。在多线程竞争下,加锁、释放锁会致使比较多的上下文切换和调度延时,引发性能问题。一个线程持有锁会致使其它全部须要此锁的线程挂起。
Java不能直接的访问操做系统底层,是经过native方法(JNI)来访问。CAS底层经过Unsafe类实现原子性操做。
ABA问题
什么是ABA问题? 好比有一个 int 类型的值 N 是 1。 此时有三个线程想要去改变它:
线程A :但愿给 N 赋值为 2
线程B: 但愿给 N 赋值为 2
线程C: 但愿给 N 赋值为 1
复制代码
此时线程A和线程B同时获取到N的值1,线程A率先获得系统资源,将 N 赋值为 2,线程B因为某种缘由被阻塞住,线程C在线程A执行完后获得 N 的当前值2。此时的线程状态:
在这个过程当中线程B获取到N的值是一个旧值,虽然和当前N的值相等,可是实际上N的值已经经历了一次 1到2到1的改变。
上面这个例子就是典型的ABA问题
怎样去解决ABA问题
给变量加一个版本号便可,在比较的时候不只要比较当前变量的值 还须要比较当前变量的版本号。Java中AtomicStampedReference 就解决了这个问题
循环时间长开销大 在并发量比较高的状况下,若是许多线程反复尝试更新某一个变量,却又一直更新不成功,循环往复,会给CPU带来很大的压力。
CAS只能保证一个共享变量的原子操做
AQS抽象的队列式同步器,是一种基于状态(state)的链表管理方式。state 是用CAS去修改的。它是 java.util.concurrent 包中最重要的基石,要学习想学习 java.util.concurrent 包里的内容这个类是关键。 ReentrantLock、CountDownLatcher、Semaphore 实现的原理就是基于AQS。想知道他怎么实现以及实现原理 能够参看这篇文章https://www.cnblogs.com/waterystone/p/4920797.html
在并发编程咱们通常使用Runable去执行异步任务,然而这样作咱们是不能拿到异步任务的返回值的,可是使用Future 就能够。使用Future很简单,只需把Runable换成FutureTask便可。使用上比较简单,这里很少作介绍。
若是咱们使用线程的时候就去建立一个线程,虽然简单,可是存在很大的问题。若是并发的线程数量不少,而且每一个线程都是执行一个时间很短的任务就结束了,这样频繁建立线程就会大大下降系统的效率,由于频繁建立线程和销毁线程须要时间。线程池经过复用能够大大减小线程频繁建立与销毁带来的性能上的损耗。
Java中线程池的实现类 ThreadPoolExecutor,其构造函数的每个参数的含义在注释上已经写得很清楚了,这里几个关键参数能够再简单说一下
最后,本文主要对Java并发编程开发须要的知识点做了简单的讲解,这里每个知识点均可以用一篇文章去讲解,因为篇幅缘由不能对每个知识点都详细介绍,我相信经过本文你会对Java的并发编程会有更近一步的了解。若是您发现还有缺漏或者有错误的地方,能够在评论区补充,谢谢。