java 提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是 jvm 实现的 synchronized,而另一个是 jdk 实现的 reentrantlock。
1. 同步一个代码块
public void func() { synchronized (this) { // ... } }
它只作用于同一个对象,如果调用两个对象上的同步代码块,就不会进行同步。
对于以下代码,使用 executorservice 执行了两个线程,由于调用的是同一个对象的同步代码块,因此这两个线程会进行同步,当一个线程进入同步语句块时,另一个线程就必须等待。
public class synchronizedexample { public void func1() { synchronized (this) { for (int i = 0; i < 10; i++) { system.out.print(i + " "); } } } } public static void main(string[] args) { synchronizedexample e1 = new synchronizedexample(); executorservice executorservice = executors.newcachedthreadpool(); executorservice.execute(() -> e1.func1()); executorservice.execute(() -> e1.func1()); }
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
对于以下代码,两个线程调用了不同对象的同步代码块,因此这两个线程就不需要同步。从输出结果可以看出,两个线程交叉执行。
public static void main(string[] args) { synchronizedexample e1 = new synchronizedexample(); synchronizedexample e2 = new synchronizedexample(); executorservice executorservice = executors.newcachedthreadpool(); executorservice.execute(() -> e1.func1()); executorservice.execute(() -> e2.func1()); }
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
2. 同步一个方法
public synchronized void func () { // ... }
它和同步代码块一样,作用于同一个对象。
3. 同步一个类
public void func() { synchronized (synchronizedexample.class) { // ... } }
作用于整个类,也就是说两个线程调用同一个类的不同对象上的这种同步语句,也会进行同步。
public class synchronizedexample { public void func2() { synchronized (synchronizedexample.class) { for (int i = 0; i < 10; i++) { system.out.print(i + " "); } } } } public static void main(string[] args) { synchronizedexample e1 = new synchronizedexample(); synchronizedexample e2 = new synchronizedexample(); executorservice executorservice = executors.newcachedthreadpool(); executorservice.execute(() -> e1.func2()); executorservice.execute(() -> e2.func2()); }
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
4. 同步一个静态方法
public synchronized static void fun() { // ... }
作用于整个类。
reentrantlock 是 java.util.concurrent(j.u.c)包中的锁。
public class lockexample { private lock lock = new reentrantlock(); public void func() { lock.lock(); try { for (int i = 0; i < 10; i++) { system.out.print(i + " "); } } finally { lock.unlock(); // 确保释放锁,从而避免发生死锁。 } } } public static void main(string[] args) { lockexample lockexample = new lockexample(); executorservice executorservice = executors.newcachedthreadpool(); executorservice.execute(() -> lockexample.func()); executorservice.execute(() -> lockexample.func()); }
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
1. 锁的实现
synchronized 是关键字,由 jvm 实现的,而 reentrantlock 是类,由 jdk 实现的。
2. 性能
新版本 java 对 synchronized 进行了很多优化,例如自旋锁等,synchronized 与 reentrantlock 大致相同。
3. 等待可中断
reentrantlock 可以获取锁的等待时间并可以进行设置,这样避免了死锁。
4. 公平锁
公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁。
synchronized 中的锁是非公平的,reentrantlock 默认情况下也是非公平的,但是也可以是公平的。
5. 锁绑定多个条件
一个 reentrantlock 可以同时绑定多个 condition 对象,灵活地实现多路通知。
6. 机制
synchronized 操作mark world,reentrantlock 调用unsafe类的park()方法
除非需要使用 reentrantlock 的高级功能,否则优先使用 synchronized。这是因为 synchronized 是 jvm 实现的一种锁机制,jvm 原生地支持它,而 reentrantlock 不是所有的 jdk 版本都支持。并且使用 synchronized 不用担心没有释放锁而导致死锁问题,因为 jvm 会确保锁的释放。
当多个线程可以一起工作去解决某个问题时,如果某些部分必须在其它部分之前完成,那么就需要对线程进行协调。
在线程中调用另一个线程的 join() 方法,会将当前线程挂起,而不是忙等待,直到目标线程结束。
对于以下代码,虽然 b 线程先启动,但是因为在 b 线程中调用了 a 线程的 join() 方法,b 线程会等待 a 线程结束才继续执行,因此最后能够保证 a 线程的输出先于 b 线程的输出。
public class joinexample { private class a extends thread { @override public void run() { system.out.println("a"); } } private class b extends thread { private a a; b(a a) { this.a = a; } @override public void run() { try { a.join(); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("b"); } } public void test() { a a = new a(); b b = new b(a); b.start(); a.start(); } } public static void main(string[] args) { joinexample example = new joinexample(); example.test(); }
a
b
调用 wait() 使得线程等待某个条件满足,线程在等待时会被挂起,当其他线程的运行使得这个条件满足时,其它线程会调用 notify() 或者 notifyall() 来唤醒挂起的线程。
它们都属于 object 的一部分,而不属于 thread。
只能用在同步方法或者同步控制块中使用,否则会在运行时抛出 illegalmonitorstateexception。
使用 wait() 挂起期间,线程会释放锁。这是因为,如果没有释放锁,那么其它线程就无法进入对象的同步方法或者同步控制块中,那么就无法执行 notify() 或者 notifyall() 来唤醒挂起的线程,造成死锁。
public class waitnotifyexample { public synchronized void before() { system.out.println("before"); notifyall(); } public synchronized void after() { try { wait(); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("after"); } } public static void main(string[] args) { executorservice executorservice = executors.newcachedthreadpool(); waitnotifyexample example = new waitnotifyexample(); executorservice.execute(() -> example.after()); executorservice.execute(() -> example.before()); }
before
after
wait() 和 sleep() 的区别
java.util.concurrent 类库中提供了 condition 类来实现线程之间的协调,可以在 condition 上调用 await() 方法使线程等待,其它线程调用 signal() 或 signalall() 方法唤醒等待的线程。
相比于 wait() 这种等待方式,await() 可以指定等待的条件,因此更加灵活。
使用 lock 来获取一个 condition 对象。
public class awaitsignalexample { private lock lock = new reentrantlock(); private condition condition = lock.newcondition(); public void before() { lock.lock(); try { system.out.println("before"); condition.signalall(); } finally { lock.unlock(); } } public void after() { lock.lock(); try { condition.await(); system.out.println("after"); } catch (interruptedexception e) { e.printstacktrace(); } finally { lock.unlock(); } } } public static void main(string[] args) { executorservice executorservice = executors.newcachedthreadpool(); awaitsignalexample example = new awaitsignalexample(); executorservice.execute(() -> example.after()); executorservice.execute(() -> example.before()); }
before
after
免费java高级资料需要自己领取,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo高并发分布式等教程,一共30g。
传送门:https://mp.weixin.qq.com/s/jzddfh-7ynudmkjt0irl8q
如对本文有疑问, 点击进行留言回复!!
sap cloud platform destination的配置
springcloud中feign调用处理mybatis-plus Ipage反序列化问题。
Flume 史上最全面的大数据学习第十篇(一) 别再说不知道flume是什么了
网友评论