Java并发

This commit is contained in:
罗祥
2019-11-26 14:45:55 +08:00
parent 9b162124a8
commit 3884f30ffd
6 changed files with 386 additions and 7 deletions

View File

@ -32,6 +32,7 @@ public class AwaitAndSignal {
Thread thread1 = new Thread(new IncreaseTask());
thread1.start();
Thread.sleep(2000);
// 必须要再次获取该重入锁否则会抛出IllegalMonitorStateException异常
lock.lock();
condition.signal();
lock.unlock();

View File

@ -70,7 +70,7 @@ public class ReadWriteLock {
public static void main(String[] args) throws InterruptedException {
// 耗时2秒写锁是互斥的,但读锁是并行的
// 写锁是排它的,但读锁是共享的耗时3秒左右
for (int j = 0; j < 2; j++) {
Thread thread = new Thread(new Write(writeLock, String.valueOf(j)));
thread.start();
@ -81,7 +81,7 @@ public class ReadWriteLock {
}
// 使用重入锁时,读锁彼此之间也是互斥的
// 使用重入锁时耗时20秒左右
for (int j = 0; j < 2; j++) {
Thread thread = new Thread(new Write(reentrantLock, String.valueOf(j)));
thread.start();

View File

@ -8,8 +8,9 @@ public class J1_ThreadUnsafe {
private static int i = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new IncreaseTask());
Thread thread2 = new Thread(new IncreaseTask());
IncreaseTask task = new IncreaseTask();
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
// 等待线程结束再打印返回值

View File

@ -21,9 +21,9 @@ public class J3_WaitAndNotify {
}).start();
new Thread(() -> {
synchronized (object) {
System.out.println("线程2开始操作");
System.out.println("对象object唤醒");
object.notify();
System.out.println("线程2后续操作");
}
}).start();
}

View File

@ -32,10 +32,11 @@ public class J5_NotifyAll {
}).start();
new Thread(() -> {
synchronized (object) {
System.out.println("线程3开始操作");
System.out.println("对象object唤醒");
// 如果是object.notify()则是随机唤醒任意一个等待
object.notifyAll();
System.out.println("线程3后续操作");
}
}).start();
}