多线程编程

This commit is contained in:
罗祥
2019-11-18 09:31:03 +08:00
parent 2ffc0a3a94
commit 910790be8c
39 changed files with 1605 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.heibaiying.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 等待与唤醒
*/
public class AwaitAndSignal {
private static ReentrantLock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
static class IncreaseTask implements Runnable {
@Override
public void run() {
try {
lock.lock();
String threadName = Thread.currentThread().getName();
System.out.println(threadName + "等待通知...");
condition.await();
System.out.println(threadName + "获得锁");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new IncreaseTask());
thread1.start();
Thread.sleep(2000);
lock.lock();
condition.signal();
lock.unlock();
}
}