java进阶-第十五讲 JUC
1 生产者消费者问题
第一版我们是用synchronized关键字和Object类中的wait()和notifyAll()
在生产者和消费者问题中:synchronized 搭配 wait()和notifyAll()
注意事项:资源类、线程、操作--->注意虚假唤醒(判断不能使用if,要用while)
在生产者消费者问题中:1判断,2操作,3通知
synchronized只能锁对象,加锁的地方要么是方法,要么是代码块(方法中的代码块)!
为什么不能在方法之外呢?因为它锁的是对象。
什么是线程不安全?多个线程同时对一个资源进行写操作的时候,也就是修改数据的时候
就可能发生线程安全问题。
CPU调度问题:限时抢答
时间片轮转。每个抢到CPU执行权的线程,CPU给它执行时间,执行时间结束,
该线程处于就绪状态,继续争抢CPU执行权。
这叫做"限时抢答"。抢到答题权的人,只能在规定时间内完成答题。
这个时间不固定。有可能是1ms,有可能是1s。
限时和抢都是CPU干的。不是线程干的。
多线程操作1个对象:
1 黎睿 1s 开头
1 彭瑞琪 2s 开头--中间
1 李昂 3s 开头--中间--结尾1
1 黎睿 3s 开头--中间--结局2
1 彭瑞琪 3s 开头--中间--结局3
如果多线程操作一个资源的时候,只是读(readonly),那么有必要加锁吗?没必要
如果多线程操作一个资源的时候,有读有写(read and write),有必要加锁吗?要
所以:对于集合和Map来讲,是不是都涉及到读和写,所以多线程情形下,要确保线程安全。
生产者消费者问题:
synchronized 搭配 wait() 和 notify()/notifyAll()
wait(long timeout),如果在timeout之前有notify或者notifyAll,我就醒了
否则我最多等你timeout这么多毫秒。
JUC:java.util.concurrent JUC又叫做并发包。
java.util.concurrent.locks 涉及到锁
java.util.concurrent.atomic
ReentrantLock:
public class Test01 {
private Lock lock = new ReentrantLock();
public void m() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "准备执行!");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + "执行完毕!");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Test01 test01 = new Test01();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
test01.m();
}, String.valueOf(i)).start();
}
}
}
...............
ReentrantLock的标准写法:
Lock l = ...;
l.lock();
try {
} finally {
l.unlock();
}
当然,也可以加上catch语句。
2 使用ReentrantLock解决生产者消费者问题
public Condition newCondition() {
return sync.newCondition();
}
当我们使用ReentrantLock来实现生产者消费者问题的时候:
1. 要使用到Condition接口,
public class Phone {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private int num;
public Phone() {
}
public Phone(int num) {
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "Phone{" +
"num=" + num +
'}';
}
public void produce() throws InterruptedException {
lock.lock();
try {
while (num != 0) {
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + "\t --->生产 " + num);
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void sale() throws InterruptedException {
lock.lock();
try {
while (num == 0) {
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName() + "\t --->卖后剩余 " + num);
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Client {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产1").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.sale();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费1").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产2").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.sale();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费2").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "生产3").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
phone.sale();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "消费3").start();
}
}
public class PassBall {
private Lock lock = new ReentrantLock();
int num = 0;
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
public void passFirst() {
lock.lock();
try {
while (num != 0) {
c1.await();
}
num++;
System.out.println(Thread.currentThread().getName() + "把球传给2号球员!");
c2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void passSecond() {
lock.lock();
try {
while (num != 1) {
c2.await();
}
num--;
System.out.println(Thread.currentThread().getName() + "把球传给1号球员!");
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Game {
public static void main(String[] args) {
PassBall passBall = new PassBall();
new Thread(()->{
passBall.passFirst();
},"1号").start();
new Thread(()->{
passBall.passSecond();
},"2号").start();
}
}
3 第三种创建线程的方式
复习一下以前的方式:
1.extends Thread 重写run方法,启动使用start
2.implements Runnable 重写run方法,启动借助new Thread(Runnable r).start()
3.实现Callable 重写call()方法
区别:前两种线程都是没有返回值的。run方法都没有返回值。第三种方式call()有返回值
Interface Callable<V>
V call()
Computes a result, or throws an exception if unable to do so.
API上说它跟Runnable类似,也就是说Callable的实现类是没有能力启动线程的。
它还得依赖Thread类来启动线程。
Thread类有没有一个构造器的参数是Callable,如果有那就简单了
线程操作资源类。new Thread(()->{instance.method();},"A").start();
Thread类没有构造器中的参数是Callable的,只有Runnable的,怎么办呐?
往下怎么走?
只能找Runnable接口,看看Runnable接口的实现类有没有一个含有Callable
的构造器。
Thread t = new Thread(Runnable的实现类);
Runnable的实现类中如果有一个类A(Callable的实现类)
Runnable实现类中有一个FutureTask类
它的构造
FutureTask(Callable<V> callable)
Creates a FutureTask that will, upon running, execute the given Callable.
这就好办了。
new Thread(new FutureTask(Callable<V> c)).start();
要解决的问题是Callable<V>的实现类。
Callable是函数式接口,所以可以写lambda表达式。匿名实现。
new Thread(new FutureTask(new Callable<Object>(){
@Override
public Object call() {
.....
return obj;
}
})).start();
这种方式能拿到返回值吗?不能!
真正能拿到返回值的做法:
FutureTask f = new FutureTask(new Callable<Object>(){
@Override
public Object call() {
.....
return obj;
}
});
new Thread(f,"A").start();
Object obj = f.get();
........
问:get()方法会阻塞吗?会阻塞。在计算结果没出来之前,get方法之后的代码都会阻塞。
实例代码:
public class Compute {
public int add(int a, int b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
Compute compute = new Compute();
FutureTask<Integer> ft = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
TimeUnit.SECONDS.sleep(10);
return compute.add(10,20);
}
});
new Thread(ft,"A").start();
try {
System.out.println("正在计算结果!!请等待!");
System.out.println(ft.get());
System.out.println("计算结果完成!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
4 Callable的方式有什么用?
应用场景:
学java一定要知道应用场景。
1. get方法会阻塞。get方法应该放在程序的什么位置?
2. 先弄清楚为什么要在程序中开这个线程呢?假如:main线程中没有其他线程
然后,其中有个方法要执行1天才会得到结果。但是它是第一个被执行的方法。
其他的方法在该方法后面,它们只执行很短的时间。
FutureTask:为什么交做未来任务,其实它告诉我们,这个东西会在未来某个时刻被执行
或者是未来某个时刻执行结束返回一个结果。
为什么要并发:提高效率,提高执行效率,效率怎么衡量,单位时间内干了多少活。
程序的执行效率单位时间内处理了多少业务逻辑。时间上的效率。
java中空间上的效率就是我们如何去管理我们的对象,让有限的内存合理被使用。
public class Service {
public Integer s1() {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("s1执行完毕!");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
}
public Integer s2() {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("s2执行完毕!");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
}
public Integer s3() {
try {
TimeUnit.SECONDS.sleep(10);
System.out.println("s3执行完毕!");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
}
public Integer s4() {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println("s4执行完毕!");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 5;
}
}
public class ServiceTest {
public static void main(String[] args) {
Service service = new Service();
FutureTask<Integer> ft = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return service.s3();
}
});
new Thread(ft,"A").start();
Integer s1 = service.s1();
Integer s2 = service.s2();
Integer s4 = service.s4();
try {
System.out.println(s1+s2+s4+ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
5 补充一个定时器
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse("2021-2-22 13:51:00");
} catch (ParseException e) {
e.printStackTrace();
}
TimerTask tt = new TimerTask() {
@Override
public void run() {
System.out.println(sdf.format(new Date())+" tt正在执行");
}
};
timer.schedule(tt,date,5000);
}
}
6 死锁
什么叫做死锁:A 占用 B的资源,不释放,且B占用A的资源不释放,双方互不相让,造成死锁。
有名的故事:哲学家吃饭的故事。5个哲学家坐在1张饭桌上吃饭。每个人持有1根筷子。
要能迟到饭,必须要有一双筷子。A -- B -- C -- D -- E -- A
但是他们不给对象自己的筷子。死锁。然后都饿死了。
怎么写死锁?
public class DeadLock {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
new Thread(()->{
synchronized (o1) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
}
}
},"A").start();
new Thread(()->{
synchronized (o2) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
}
}
},"B").start();
}
}
7 JUC下的其他类
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t 离开513");
cdl.countDown();
}, String.valueOf(i+1)).start();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("prq 关门,最后离开!");
}
}
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(7, ()->{
System.out.println("聚齐七颗龙珠,召唤神龙!");
});
for (int i = 0; i < 7; i++) {
final int tem = i + 1;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t 收集了第:" + tem);
try {
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i+1)).start();
}
}
}
public class SemaphoreTest {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "\t 抢到车位!");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "\t 离开车库!");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i + 1)).start();
}
}
}