多线程
9.线程同步
发生在多个线程操作同一个资源
并发:同一个对象被多个线程同时操作(抢票)
public class UnsaffeBuyTicket {
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 (true){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account {
double money;//余额
String name;//卡名
public Account(double money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread {
Account account;//账户
//取了多少钱
double drawingMoney;
//现在手里有多少钱
double nowMoney;
public Drawing(Account account, double 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 = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
//Thread.currentThread().getName() 等价于 this.getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
//线程不安全的集合
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();
}
System.out.println(list.size());
}
}
10.死锁
某一个同步代码块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0,"灰姑娘");
Makeup g2=new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick=new Lipstick();
static Mirror mirror=new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
Makeup(int choice,String girlName){
this.choice=choice;
this.girlName=girlName;
}
@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.girlName+"获得口红的锁");
Thread.sleep(1000);
synchronized (mirror) {//一秒钟后获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
}
}
//解决死锁:不能抱对方的锁
// synchronized (mirror) {//一秒钟后获得镜子的锁
// System.out.println(this.girlName + "获得镜子的锁");
// }
}else{
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {//一秒钟后获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
//解决死锁:不能抱对方的锁
// synchronized (lipstick) {//一秒钟后获得口红的锁
// System.out.println(this.girlName + "获得口红的锁");
// }
}
}
}
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件;若干进程之间形成一种头尾相接的循环等待资源关系
10.Lock(锁)
//测试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 ticketNum = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();//加锁
if (ticketNum > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNum--);
} else {
break;
}
} finally {
//解锁
lock.unlock();
}
}
}
}
synchronized和Lock的对比:
- Lock是显式锁(手开启和管闭锁,别忘记管闭锁)synchronized是隐式锁,出了作用域自动释放
- Lock 只有代码块锁,synchronized有代码锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好地扩展性(提供更多的子类)
- 优先使用顺序:
- Lock > 同步代码块(已经进入了方法体,分配了相应资源)> t同步方法(在方法体之外)