JUC编程的学习(一)
JUC的学习(一)
1.线程和进程(回顾)
线程和进程概括:
进程:
1.一个运行的程序,qq.exe,程序的集合;
2.一个进程往往可以包含多个线程,至少一个!
3.java默认有几个? 2个 main线程 GC线程
线程:
开了一个进程比如Typora,写字,自动保存都是一个线程
对于java而言:Thread,Runnable,Callable
问题来了:java真的可以开启一个线程吗? 答案是: 开不了!java无法开启硬件,start方法里面调用了start0方法是一个本地方法。
并发编程:并发、并行
并发(多线程操作同一个资源):
- 单核CPU快速交替运行,造成并发的假象
并行(多个人一起走):
- CPU多核,多个线程可以同时执行
public class demo01 {
public static void main(String[] args) {
//获取cpu的核数
//cpu密集型 ,IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用CPU的资源 (企业看重)
线程有几个状态?
public enum State {
//新生
NEW,
//运行
RUNNABLE,
//阻塞
BLOCKED,
//等待,死死的等
WAITING,
//超时等待
TIMED_WAITING,
//终止
TERMINATED;
}
wait和sleep的区别
1.来自不同的类
wait => Object (一般不使用)
sleep=>Thread
企业中会使用JUC包下的TimeUnit来操作
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
2.关于锁的释放
wait会释放锁,而sleep会抱着锁不放。
3.使用的范围不同
wait:必须在同步代码块中,不需要捕获异常
sleep:可以在任何地方睡,需要捕获异常
2.Lock锁
1.先回顾synchronized
我们用卖票的demo来尝试
//卖票,摒弃传统的实现Runnable接口的卖票,解耦,直接在线程里面操作资源
public class SaleTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
//@FunctionalInterface 函数式接口
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sale();
}
},"黄牛A").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sale();
}
},"黄牛B").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sale();
}
},"黄牛C").start();
}
}
//资源类 OOP
class Ticket{
private int number = 30;
public synchronized void sale(){
if (number>0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票,还剩余:"+number);
}
}
//锁对象
//class
2.使用Lock来实现卖票
这是Lock的实现类。
可重入锁是最一般我们最常用的锁,可以由参数指定自己的可重入锁锁,是公平锁还是非公平锁。
public class SaleTicketdemo02 {
public static void main(String[] args) {
Ticket2 ticket2 = new Ticket2();
new Thread(()->{for (int i=1;i<=10;i++) ticket2.sale();},"黄牛A").start();
new Thread(()->{for (int i=1;i<=10;i++) ticket2.sale();},"黄牛B").start();
new Thread(()->{for (int i=1;i<=10;i++) ticket2.sale();},"黄牛C").start();
}
}
// Lock三部曲
//1.Lock lock = new ReentrantLock();
//2.lock.lock(); //上锁
//3.释放锁 lock.unlock();
class Ticket2 {
private int number = 30;
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票,还剩余:" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
}
3.Synchronized和Lock的区别(重要)
1. Synchronized是java中的关键字,而Lock是类
2. Synchronized无法获取锁的状态,而Lock可以判断是否获取到了锁
3. Synchronized会自动释放锁,而Lock需要手动去释放(unlock)
4. Synchronized 线程1(获取了锁),线程2(就一直傻等);Lock锁就不一定会一直等下去
5. Synchronized可重入锁,不可以中断,非公平;Lock,可重入锁,可以判断锁,非公平锁(可以自己设置)
6. Synchronized 适合锁少量代码同步问题,Lock适合锁大量的同步代码
7. Lock只有代码块锁,而Synchronized还有方法锁
3.生产者和消费者问题
1.传统方式
package com.xy.pc; /** * @author xiaye * @create 2020-03-18-14:56 */ import javax.xml.crypto.Data; import java.util.Date; /** * Synchronized 版本的生产者消费者 * 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒 * 线程交替执行 A B 操作同一个变量 num = 0 * A num+1 * B num-1 */ public class productConsume01 { public static void main(String[] args) { Num num = new Num(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "c").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "d").start(); } } //数据类 class Num { private int num = 0; // +1 public synchronized void increment() throws InterruptedException { while (num != 0) { //如果数字不为0,等待 wait(); } num++; System.out.println(Thread.currentThread().getName() + "===>" + num); //通知其他线程我执行完了 +1 this.notifyAll(); } // -1 public synchronized void decrement() throws InterruptedException { while (num == 0) { //如果数字等于,就等待 wait(); } num--; System.out.println(Thread.currentThread().getName() + "===>" + num); //通知其他线程我执行完了 -1 this.notifyAll(); } }
2.JUC 版
package com.xy.pc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author xiaye * @create 2020-03-18-15:25 * * JUC版本的生产者和消费者 * 使用Lock和COndition来代替syhchronized 和wait ,notifyAll */ public class productConsumeLock { public static void main(String[] args) { Num2 num = new Num2(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "D").start(); } } //数据类 class Num2 { private int num = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); // +1 public void increment() throws InterruptedException { //上锁 lock.lock(); try { while(num!=0){ //等待 condition.await(); } num++; System.out.println(Thread.currentThread().getName()+"===>"+num); //通知所有人已经+1 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { //解锁 lock.unlock(); } } // -1 public void decrement() throws InterruptedException { lock.lock(); try { while (num == 0) { //如果数字等于,就等待 condition.await(); } num--; System.out.println(Thread.currentThread().getName() + "===>" + num); //通知其他线程我执行完了 -1 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
3.指定唤醒线程,多个监视器
package com.xy.pc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author xiaye * @create 2020-03-18-16:08 * <p> * <p> * A 执行完调用B,B执行完调用C,C执行完调用A */ public class productConsumeLock02 { public static void main(String[] args) { Num3 num = new Num3(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.oprationA(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.oprationB(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { num.oprationC(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); } } //数据类 class Num3 { private int num = 1; private Lock lock = new ReentrantLock(); private Condition conditionA = lock.newCondition(); private Condition conditionB = lock.newCondition(); private Condition conditionC = lock.newCondition(); // 1 A操作 2 B操作 3 C操作 public void oprationA() throws InterruptedException { //上锁 lock.lock(); try { while (num != 1) { //等待 conditionA.await(); } num = 2; System.out.println(Thread.currentThread().getName() + "===>已经操作完成,该B了"); //通知B,操作啦 conditionB.signal(); } catch (Exception e) { e.printStackTrace(); } finally { //解锁 lock.unlock(); } } public void oprationB() throws InterruptedException { lock.lock(); try { while (num != 2) { //等待 conditionB.await(); } num = 3; System.out.println(Thread.currentThread().getName() + "===>已经操作完成,该C了"); //通知C,操作啦 conditionC.signal(); } catch (Exception e) { e.printStackTrace(); } finally { //解锁 lock.unlock(); } } public void oprationC() throws InterruptedException { lock.lock(); try { while (num != 3) { //等待 conditionC.await(); } num = 1; System.out.println(Thread.currentThread().getName() + "===>已经操作完成,该C了"); //通知A,操作啦 conditionA.signal(); } catch (Exception e) { e.printStackTrace(); } finally { //解锁 lock.unlock(); } } }