java.util工具包、包、分类
业务:普通的线程代码 Thread
Runable 没有返回值、效率相比于Callable相对较低
线程、进程,如果不能使用一句话说出来的技术,不扎实
进程:一个程序,QQ.exe Music.exe 程序的集合;
一个进程往往可以包含多个线程,至少包含一个!
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();
并发、并行
并发编程:并发、并行
并发(多个线程操作同一个资源)
并行(多个人一起行走)
package com.won.demo01;
public class Test1 {
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
2、关于锁的释放
wait会释放锁
sleep不会(抱着锁睡觉,不会释放)
3、使用的范围是不同的
wait必须在同步代码块中
sleep可以在任何地方睡
4、是否需要捕获异常
wait 不需要捕获异常
sleep 必须要捕获异常
传统 Synchronized
package com.won.demo01;
// 基本的卖票例子
/*
真正的多线程开发,公司中的开发,降低耦合性
线程就是一个单独的资源类,没有任何附属的操作
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 < 60; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"C").start();
}
}
// 资源类 OOP
class Ticket {
// 属性、方法
private int number = 50;
// 卖票的方式
// synchronized 本质:队列,锁
public synchronized void sale() {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票,剩余:" + number + "张票");
}
}
}
Lock接口
非公平锁:十分不公平,可以插队(默认)
package com.won.demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// 基本的卖票例子
/*
真正的多线程开发,公司中的开发,降低耦合性
线程就是一个单独的资源类,没有任何附属的操作
1.属性、方法
*/
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();
// 卖票的方式
// synchronized 本质:队列,锁
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 会自动释放锁;Lock必须要手动释放锁!如果不释放,死锁
4、synchronized 线程1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待下去
5、synchronized 可重入锁,不可以中断,非公平的;Lock,可重入锁,可以判断锁,非公平(可以自己设置)
6、synchronized 适合锁少量的代码同步问题;Lock 适合锁大量的同步代码!
锁是什么,如何判断锁的是谁?
面试:单例模式、排序算法、生产者和消费者模式、死锁
生产者和消费者问题 synchronized版
package com.won.pc;
/**
* 线程之间的通信问题:生产者和消费者问题 等待唤醒,通知唤醒
* 线程交替执行 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(()->{
try {
for (int i = 0; i < 10; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
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) {
// 等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,+1 完毕
this.notifyAll();
}
// -1
public synchronized void decrement() throws InterruptedException {
if (number == 0) {
// 等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,-1 完毕
this.notifyAll();
}
}
问题存在, A B C D 4个线程还安全吗? 虚假唤醒
解决方法:if 改为 while 判断
package com.won.pc;
/**
* 线程之间的通信问题:生产者和消费者问题 等待唤醒,通知唤醒
* 线程交替执行 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(()->{
try {
for (int i = 0; i < 10; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
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) {
// 等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,+1 完毕
this.notifyAll();
}
// -1
public synchronized void decrement() throws InterruptedException {
while (number == 0) {
// 等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,-1 完毕
this.notifyAll();
}
}
代码实现:
package com.won.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程之间的通信问题:生产者和消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num=0
* A num + 1
* B num - 1
*/
public class B {
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
data.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"D").start();
}
}
// 判断等待,业务,通知
class Data2 { // 数字,资源类
private int number = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
//condition.await(); // 等待
//condition.signalAll(); // 唤醒全部
// +1
public void increment() throws InterruptedException {
lock.lock();
try {
// 业务代码
while (number != 0) {
// 等待
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,+1 完毕
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// -1
public void decrement() throws InterruptedException {
lock.lock();
try {
while (number == 0) {
// 等待
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,-1 完毕
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
任何一个新的技术,绝对仅仅只是覆盖了原来的技术,一定会有新的优势和补充。
package com.won.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A 执行完调用 B,B 执行完调用 C,C 执行完调用 A
*/
public class C {
public static void main(String[] args) {
Data3 data = new Data3();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printA();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printB();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printC();
}
},"C").start();
}
}
class Data3{ // 资源类 Lock
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int number = 1; // 1 -> A; 2 -> B; 3 -> C
public void printA() {
lock.lock();
try {
// 业务,判断 -> 执行 -> 通知
while (number != 1) {
// 等待
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "=>AAAAA");
// 唤醒,唤醒指定的人 B
number = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
// 业务,判断 -> 执行 -> 通知
while (number != 2) {
// 等待
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "=>BBBBB");
// 唤醒,唤醒指定的人,C
number = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
// 业务,判断 -> 执行 -> 通知
while (number != 3) {
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "=>CCCCC");
// 唤醒,唤醒指定的人,A
number = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
如何判断锁的是谁!
对象、Class
package com.won.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁,就是关于锁的8个问题
* 1.在标准情况下,两个线程是先打印 发短信还是打电话? 1、发短信 -> 2、打电话
* 2.sendSms延迟4秒,两个线程是先打印 发短信还是打电话? 1、发短信 -> 2、打电话
*/
public class Test1 {
public static void main(String[] args) {
Phone phone = new Phone();
// 锁的存在
new Thread(()->{
phone.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone.call();
},"B").start();
}
}
class Phone{
// synchronized 锁的对象是方法的调用者!
// 两个方法用的是同一个锁,谁先拿到谁执行
public synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
}
package com.won.lock8;
import java.util.concurrent.TimeUnit;
/**
* 3.增加了一个普通方法后,先执行发短信还是hello? 普通方法
* 4.两个对象,两个同步方法,发短信还是 打电话? 打电话!
*/
public class Test2 {
public static void main(String[] args) {
// 两个对象,两个调用者,两把锁!
Phone2 phone1 = new Phone2();
Phone2 phone2 = new Phone2();
// 锁的存在
new Thread(()->{
phone1.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
class Phone2{
// synchronized 锁的对象是方法的调用者!
// 两个方法用的是同一个锁,谁先拿到谁执行
public synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
// 这里没有锁!!!不是同步方法,不受锁的影响
public void hello() {
System.out.println("hello");
}
}
package com.won.lock8;
import java.util.concurrent.TimeUnit;
/**
* 5.增加两个静态的同步方法,只有一个对象,先打印 发短信?打电话? 发短信
* 6.两个对象,增加两个静态的同步方法,先打印 发短信?打电话? 发短信
*/
public class Test3 {
public static void main(String[] args) {
// 两个对象的Class类模板只有一个,static,锁的是Class
Phone3 phone1 = new Phone3();
Phone3 phone2 = new Phone3();
// 锁的存在
new Thread(()->{
phone1.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
// Phone3唯一的一个class对象
class Phone3{
// synchronized 锁的对象是方法的调用者!
// static 静态方法
// 类一加载就有了! 锁的是 Class
public static synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public static synchronized void call() {
System.out.println("打电话");
}
}
package com.won.lock8;
import java.util.concurrent.TimeUnit;
/**
* 7.一个静态的同步方法,一个普通的同步方法,一个对象,先打印 发短信?打电话? 打电话
* 8.一个静态的同步方法,一个普通的同步方法,两个对象,先打印 发短信?打电话? 打电话
*/
public class Test4 {
public static void main(String[] args) {
// 两个对象的Class类模板只有一个,static,锁的是Class
Phone4 phone1 = new Phone4();
Phone4 phone2 = new Phone4();
// 锁的存在
new Thread(()->{
phone1.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
// Phone4唯一的一个class对象
class Phone4{
// 静态的同步方法 锁的是 Class 类模板
public static synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
// 普通的同步方法,锁的是调用者
public synchronized void call() {
System.out.println("打电话");
}
}
小结
new:this,具体的一个手机
static:Class,唯一的一个模板