第44天学习打卡(JUC 线程和进程 并发和并行 Lock锁 生产者和消费者问题 如何判断锁(8锁问题) 集合类不安全)
1.java.util工具包 包 分类
业务:普通的线程代码 Thread
Runnable 没有返回值、效率相比Callable相对较低
2.线程和进程
进程:一个程序。QQ.exe,Music.exe 程序的集合
一个进程往往可以包含多个线程,至少包含一个!
Java默认有几个线程:2个 main、GC
线程:开了一个进程Typora,写字(一个线程在输入),自动保存(线程负责的)
对于Java而言开启线程的方式:Thread、Runnable、Callable
Java真的可以开启线程吗? 开不了
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
//本地方法 调用底层的C++,java是运行在虚拟机上的,无法操作硬件
private native void start0();
并发 、并行
并发编程:并发 并行
并发(多线程操作桶一个资源)
并行(多个人一起行走)
并发:若CPU只有一核(一瞬间只能处理一个东西),想要模拟出来多条线程,则需要快速交替。
并行:若CPU多核,多个线程可以同时执行,用线程池提高性能
package com.kuang.demo06;
public class Test1 {
public static void main(String[] args) {
//获取CPU的核数
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用CPU的资源
线程有几个状态
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
//线程新生
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
//运行状态
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
//阻塞
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
//等待
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
//超时等待 死死的等
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
//终止
TERMINATED;
}
wait/sleep区别
1.来自不同的类
wait=>Object
sleep=>Thread
TimeUnit.DAYS.sleep(1);
TimeUnit.SECONDS.sleep(2);
2关于锁的释放
wait会释放锁
sleep不会释放锁 抱着锁睡觉不会放锁
3使用范围不同
wait:必须在同步代码块中
sleep:可以在任何地方
4 是否需要捕获异常
wait不需要捕获异常
sleep必须要捕获异常
3、Lock锁(重点)
传统synchronized
package com.kuang.demo06;
//基本的卖票例子
/**
* 真正的多线程开发,公司中的开发,降低耦合性
*线程就是一个单独的资源类,没有任何附属的操作
* 1.属性、方法
*/
public class SaleTicketDemo01 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源丢入线程
Ticket ticket = new Ticket();
//@FunctionalInterface 函数式接口,jdk1.8后 lambda表达式(参数)->{代码}
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"C").start();
}
}
//资源类OOP
class Ticket{
//属性,方法
private int number = 30;
//卖票的方式
//synchronized 本质:队列 锁
public synchronized void sale(){
if (number>0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"票,剩余"+number);
}
}
//锁 锁的是对象
//锁class
}



公平锁:十分公平:可以先来后到(即排队)
非公平锁:十分公平:可以插队(默认)
package com.kuang.demo06;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTicketDemo02 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源丢入线程
Ticket2 ticket = new Ticket2();
//@FunctionalInterface 函数式接口,jdk1.8后 lambda表达式(参数)->{代码}
new Thread(()->{ for (int i = 0; i < 40; i++) ticket.sale(); },"A").start();
new Thread(()->{ for (int i = 0; i < 40; i++) ticket.sale(); },"B").start();
new Thread(()->{ for (int i = 0; i < 40; i++) ticket.sale(); },"C").start();
}
}
//Lock三部曲
// 1.new ReentrantLock();
//2.Lock.lock();//加锁
//3.finally=> 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();//解锁
}
}
}
Synchronized和Lock区别
1.Synchronized 是内置的java关键字,Lock是一个java类
2.Synchronized 无法判断获取的状态,Lock可以判断是否获取到了锁
3.Synchronized 会自动释放锁,loack必须要手动释放锁!如果不释放,会造成死锁
4.Synchronized 线程1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待下去。
5.Synchronized 可重入锁,不可以中断的,非公平;Lock,可重入锁,可以判断锁,非公平(可以自己设置);
6.Synchronized 适合锁少量的代码同步问题,Lock适合锁大量的同步代码!
4.生产者和消费者问题
面试的时候:单例模式 排序算法 生产者和消费者 死锁
Synchronized 版 wait notify
juc lock
生产者和消费者问题Synchronized 版
package com.kuang.productorcous;
/**
*线程之间的通信问题:生产者和消费者问题!等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num = 0
* A num + 1
* B num - 1
*/
public class A {
public static void main(String[] args) {
//创建一个资源类
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++)
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
}
}
//判断等待 业务 通知
class Data{
//数字 资源类是独立耦合的
private int number = 0;
//+1
//只要是并发编程一定要有锁
public synchronized void increment() throws InterruptedException {
if (number!=0){//0的时候干活
//等待操作
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我+1完毕了
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
if (number==0){//1的时候干活
//等待
this.wait();
}number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我-1完毕了
this.notifyAll();
}
}
问题存在:A B C D4个线程!存在虚假唤醒

if改为while判断
package com.kuang.productorcous;
/**
*线程之间的通信问题:生产者和消费者问题!等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num = 0
* A num + 1
* B num - 1
*/
public class A {
public static void main(String[] args) {
//创建一个资源类
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++)
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++)
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++)
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"D").start();
}
}
//判断等待 业务 通知
class Data{
//数字 资源类是独立耦合的
private int number = 0;
//+1
//只要是并发编程一定要有锁
public synchronized void increment() throws InterruptedException {
while (number!=0){//0的时候干活
//等待操作
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
