多个线程在操作同一个资源
synchronized
wait、notify(一定要在线程同步中使用,并且是同一个锁的资源。wait释放锁,notify不释放锁)
public void runBase(){
Object lock = new Object();
new Thread(){
public void run(){
synchronized (lock){
try {
lock.wait();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
synchronized (lock){
lock.notify();
}
}
}.start();
}
lock(Condition)
public void run02(){
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(){
public void run(){
try {
lock.lock();
condition.await();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}.start();
new Thread(){
public void run(){
try {
lock.lock();
condition.signal();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}.start();
}
CountDownLatch
有一个任务A,它要等待其他4个任务执行完毕之后才能执行
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(4);
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ",子线程开始执行...");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ",子线程结束执行...");
}
}).start();
for(int i = 0;i<10;i++){
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(500);
System.out.println("开始执行:" + Thread.currentThread().getName());
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
Volatile(volatile 的读性能消耗与普通变量几乎相同,但是写操作稍慢)
1.保证此变量对所有的线程的可见性
2.禁止指令重排序优化。(赋值后多执行了一个“load addl $0x0, (%esp)”操作,这个操作相当于一个内存屏障(指令重排序时不能把后面的指令重排序到内存屏障之前的位置))
3.并不能保证原子性。(还是不安全的)
原子类(Atomic ,比较再交换)
是一种乐观锁
AtomicBoolean、AtomicInteger、AtomicLong、AtomicReference等
public void atomicRun(){
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
if(atomicBoolean.compareAndSet(true,false)){
System.out.println("true就执行,并同时把值改为false");
}
}
CyclicBarrier(大家准备好,一起跑。)
public static void main(String[] args) {
CyclicBarrier cyclicBarrier=new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("等待执行:" + Thread.currentThread().getName());
cyclicBarrier.await();
System.out.println("开始执行:" + Thread.currentThread().getName());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}).start();
}
}
Semaphore(设置茅坑数量,无论多少人,都得竞争这几个茅坑)
public static void main(String[] args) {
Semaphore semp = new Semaphore(5);
for (int i = 0; i < 50; i++) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("排队上厕所:" + Thread.currentThread().getName());
semp.acquire();//申请资源
System.out.println("当前厕所剩余数:" + semp.availablePermits());
Thread.sleep(500);
System.out.println("厕所上完了:" + Thread.currentThread().getName());
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
semp.release();//释放资源
}
}
}).start();
}
}