线程同步
1.发生在多个线程操作同一个资源
2.并发:同一个对象被多个线程同时操作
3.于是,就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
4.线程同步的形成条件:队列+锁(synchronized)
5.线程同步也存在问题:
- 性能降低:一个线程持有锁会导致其他所有需要此锁的线程挂起;在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题。
- 性能倒置:如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题。
三个不安全的案例
1.不安全的买票
package com.zhang.syn;
//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"漂亮的羡羡").start();
new Thread(station,"可靠的野哥").start();
new Thread(station,"温柔的魏魏").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
//模拟延时,放大问题的发生性
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
2.不安全的取钱
package com.zhang.syn;
//不安全的取钱
//两个人去银行取钱
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "份子钱");
Drawing you = new Drawing(account,50,"你");
Drawing teammates = new Drawing(account,100,"姐妹");
you.start();
teammates.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if (account.money-drawingMoney < 0){
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money -= drawingMoney;
//你手里的钱
nowMoney += drawingMoney;
System.out.println(account.name+"余额为"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
3.线程不安全的集合
package com.zhang.syn;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法及同步块
三个案例重写
1.不安全的买票
(只加了synchronized关键字)
package com.zhang.syn;
//不安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"漂亮的羡羡").start();
new Thread(station,"可靠的野哥").start();
new Thread(station,"温柔的魏魏").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
//模拟延时,放大问题的发生性
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
2.不安全的取钱
(加了synchronized(obj){}方法块)
package com.zhang.syn;
//不安全的取钱
//两个人去银行取钱
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "份子钱");
Drawing you = new Drawing(account,50,"你");
Drawing teammates = new Drawing(account,100,"姐妹");
you.start();
teammates.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
//synchronized 默认锁的是this,于是用到同步块
@Override
public void run() {
synchronized (account){//方法丢到方法里面,块丢到块里面
//判断有没有钱
if (account.money-drawingMoney < 0){
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money -= drawingMoney;
//你手里的钱
nowMoney += drawingMoney;
System.out.println(account.name+"余额为"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
}
3.线程不安全的集合
(用synchronized(obj){}方法块锁了对象)
package com.zhang.syn;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
安全的类CopyOnWriteArrayList
(JUC包下的)(JUC是并发领域的)
package com.zhang.syn;
import java.util.concurrent.CopyOnWriteArrayList;//JUC并发包,Callable也需导入这个包,Callable是关于并发编程的
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();//集合都加泛型约束,注意代码规范!!
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.size());
}
}
死锁
(相互等待对方的资源,于是都停下来了)
package com.zhang.Thread;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup lover1 = new Makeup(0,"羡羡");
Makeup lover2 = new Makeup(1,"染染");
lover1.start();
lover2.start();
}
}
//红发带
class Lipstick{
}
//扇子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String loverName;//使用化妆品的人
Makeup(int choice, String loverName){
this.choice = choice;
this.loverName = loverName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0){
synchronized (lipstick){//获得红发带的锁
System.out.println(this.loverName + "获得红发带的锁");
Thread.sleep(1000);
}
synchronized (mirror){//一秒钟之后想获得扇子
System.out.println(this.loverName + "获得扇子的锁");
}
}else {
synchronized (mirror){//获得扇子的锁
System.out.println(this.loverName + "获得扇子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//一秒钟之后想获得红发带
System.out.println(this.loverName + "获得红发带的锁");
}
}
}
}
Lock(锁)
package com.zhang.gaoji;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
//
class TestLock2 implements Runnable{
int ticketNums =10;
//定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try{
lock.lock();//加锁
if (ticketNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
线程通信(生产者消费者问题)
管程法
package com.zhang.gaoji;
//测试:生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){//构造器方便创造对象
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {//生产100瓶酒
container.push(new Wine(i));
System.out.println("生产了" + i +"瓶酒");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){//构造器方便创造对象
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->" + container.pop().id +"瓶酒");
}
}
}
//产品
class Wine{
int id;//产品编号
public Wine(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Wine[] wines = new Wine[10];
//容器的计数器
int count = 0;
//生产者放入产品
public synchronized void push(Wine wine){
//如果容器满了,就需要等待消费者消费
if (count == wines.length){
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
wines[count] = wine;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Wine pop(){
//判断能否消费
if (count == 0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Wine wine = wines[count];
//喝完了,通知生产者生产
this.notifyAll();
return wine;
}
}
信号灯法
package com.zhang.gaoji;
//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
public static void main(String[] args) {
Video video = new Video();
new Actor(video).start();
new Viewer(video).start();
}
}
//生产者-->演员
class Actor extends Thread{
Video video;
public Actor(Video video){
this.video = video;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2 == 0){
this.video.play("我们的歌");
}else {
this.video.play("最美逆行者");
}
}
}
}
//消费者-->观众
class Viewer extends Thread{
Video video;
public Viewer(Video video){
this.video = video;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
video.watch();
}
}
}
//产品-->节目
class Video{
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员潘达表演了:" + voice);
//通知观众观看
this.notifyAll();//通知唤醒
this.voice = voice;//voice更新了
this.flag = !this.flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众蔡丁观看了:" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
package com.zhang.gaoji;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行 Runnable接口的一个实现类
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
线程创建总结
1.继承Thread类
2.实现Runnable接口
3.实现Callable接口
package com.zhang.gaoji;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();//Thread()代理类
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();//可以实现Runnable接口 因为FutureTask继承了Runnable接口
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}