线程优先级
优先级简述:
-
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
-
线程的优先级用数字表示,范围1~10.
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5
-
使用以下方式改变获取优先级
-
getPriorty(),setPriority(int xx)
优先级的设定建议在star()调度前
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调度了,完全看CPU的心情。也就是说你买一百张彩票,你优先获得奖的概率大于一张,但是并不意味着你买一白张票就能的奖,完全是看脸。
-
代码:
public class Priority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
TestPriority testPriority = new TestPriority();
Thread thread1 = new Thread(testPriority);
Thread thread2 = new Thread(testPriority);
Thread thread3 = new Thread(testPriority);
Thread thread4 = new Thread(testPriority);
Thread thread5 = new Thread(testPriority);
//设置优先级,启动
thread1.start();
thread2.setPriority(6);
thread2.start();
thread3.setPriority(1);
thread3.start();
thread4.start();
thread5.setPriority(Thread.MAX_PRIORITY); //最大优先级为10
thread5.start();
}
}
class TestPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
线程协作
三大不安全案例
买票问题
黄牛党,小明,小红三人抢票。
代码
public class UnsaftBuyTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket,"黄牛党").start();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
}
}
class Ticket implements Runnable{
private int ticket = 10;
private boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy(flag);
Thread.sleep(100); //设置延时
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到" + ticket--);
}
}
//判断系统票数,控制程序停止
private void buy(boolean flag) {
if (ticket < 0 ){
this.flag = false;
return;
}
}
}
图示
如上面程序所运行的结果,会出现票抢到的数字为负数的情况,这是买票机构不允许发生的。
银行取钱
代码
public class Unsaftbank {
public static void main(String[] args) {
Account account = new Account(2000,"工资卡");
Bank xioaming = new Bank(account,1000,"小明");
Bank xiaohong = new Bank(account,2000,"小红");
xioaming.start();
xiaohong.start();
}
}
//账户
class Account{
int money;
String user;
public Account(int money, String user) {
this.money = money;
this.user = user;
}
}
//银行账户取款
class Bank extends Thread{
Account account;
//取了多少钱
int givemoney;
//现在手里的余额
int nowmoney;
public Bank(Account account,int givemoney,String name) {
super(name);
this.account = account;
this.givemoney = givemoney;
}
@Override
public void run() {
//判断账户余额
if (account.money - givemoney < 0){
System.out.println(Thread.currentThread().getName() + ",钱不够,请及时充值");
return ;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
//卡内剩余余额
account.money = account.money - givemoney;
//手里的钱
nowmoney = givemoney + nowmoney;
System.out.println(account.user + "余额为:" + account.money);
System.out.println(Thread.currentThread().getName() + "手中取后现有" + nowmoney + " ");
}
}
图示
如图就会出现工资卡为负数的情况
线程不安全的集合
代码
import java.util.ArrayList;
import java.util.List;
public class UnsaftList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
图示
ArrayList与Thread中的两个线程同时相加在同一个位置进行覆盖,会导致线程不会跑完10000,但是好的电脑可以出现跑完10000的情况
线程同步
概述
- 案例:现实生活中,我们会遇到“同一个资源,多个人想使用”的问题,比如,食堂排队打饭,每个人都想吃饭,最天然的解决办法就是,排队,一个个的来。
- 处理多个线程问题时,多个线程访问同一个对象,并且某些还想修改对象,这时候就需要线程同步。线程同步就是一种等待机制,多个需要同时访问此对象的线程进入这个对象等待池形成队列,等待使用完毕,下一个线程再使用。
- 同步形成条件:队列 + 锁。
- 由于同一进程的多个线程共享一块存储空间,在方便的同时,也带来了访问的冲突问题,为了保证数据的方法中被访问的正确性,在访问的同时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起。
- 在多个线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题。
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。如:你上小号(优先级高),也就一分钟的时间,但是有个想上大号(优先级低)的赶在你前面上厕所,一蹲就是半个小时,你膀胱都憋炸了。
同步方法
-
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种方法:
synchronized方法
和synchronized块
同步方法:public synchronized void method(int args){}
-
synchronized方法
控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法
都必须都必须获得调用该方法的对象的锁才能执行,否则线程会住阻塞,方法一旦执行,就独占该锁
,直到该方法返回才释放锁,会面被阻塞的线程才能获得这个锁,继续执行。缺陷:若将一个大的方法申明为synchronized将会影响效率。 eg.你在排队上厕所,每个人都有权利关厕所的门,进来一个人上厕所关上门,后面的人等待前一个人上完厕所,其过程势必会有等待时间。
使用方法
-
查看三大不安全案例我们只需要做以下的改动
-
抢票问题:
private synchronized void buy(boolean flag)
-
取钱问题:
ssynchronized默认锁的是this,即Bank,而我们锁住了银行没有用,还是要在里面取钱,我们需要锁住账户,这时候我们就需要使用
synchronized块
来锁。格式为synchronized (锁的对象){执行的动作}
。synchronized (account){ //判断账户余额 if (account.money - givemoney < 0){ System.out.println(Thread.currentThread().getName() + ",钱不够,请及时充值"); return ; } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } //卡内剩余余额 account.money = account.money - givemoney; //手里的钱 nowmoney = givemoney + nowmoney; System.out.println(account.user + "余额为:" + account.money); System.out.println(Thread.currentThread().getName() + "手中取后现有" + nowmoney + " "); }
-
同步方法的弊端
-
方法里面需要修改的内容才需要锁,锁太多,浪费资源。
队列和锁
- 队列:假如你在食堂打饭,旁边的人到站的好好的,前面突然来了三个大汉不想排队直接跑到前面插队,三人争执谁也没有打到饭,还会引来周围人的不满,所以队列就显得很重要。
- 锁:类比于我们去旅游玩耍,中途你想上厕所,但是是公共厕所得排队一个一个来,上厕所你不可能把门开着上,为了保护自己的隐私,于是乎你会把厕所们关上。
死锁
-
多个线程各自占有一些共享的资源,并且相互等待其他线程占有的资源才能运行,这就形成了双方两个或者多个线程都在等待对方释放内存,出现停止的现象。当某个同步块出现同时拥有“两个以上对象说锁”时,就会发生“死锁”的问题。
举个例子:你和你的小伙伴想交换零食吃,然而双方都想着另一方先交换,这时候是线程所说的双方两个或者多个线程都在等待对方释放内存。
代码:
public class Sharthing {
public static void main(String[] args) {
Things p1 = new Things(0,"jack");
Things p2 = new Things(1,"tom");
new Thread(p1).start();
new Thread(p2).start();
}
}
class Chips{
}
class Candies{
}
class Things implements Runnable{
static Chips chips = new Chips();
static Candies candies = new Candies();
int choice;
String name;
public Things(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
MakeThing();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void MakeThing () throws InterruptedException {
if (choice == 0){
synchronized (chips){//获得薯片
System.out.println(this.name + "获得薯片的锁");
Thread.sleep(1000);
synchronized (candies){//一秒钟后获得糖果
System.out.println(this.name + "获得糖果的锁");
}
}
}else {
synchronized (candies){
System.out.println(this.name + "获得糖果的锁");
Thread.sleep(1000);
synchronized (chips){//一秒钟后获得薯片
System.out.println(this.name + "获得薯片的锁");
}
}
}
}
}
图示:
解决方案:将第二个锁移至外面
if (choice == 0){
synchronized (chips){//获得薯片
System.out.println(this.name + "获得薯片的锁");
Thread.sleep(1000);
}
//将下锁移动与类似的位置
synchronized (candies){//一秒钟后获得糖果
System.out.println(this.name + "获得糖果的锁");
}
}
图示:
Lock锁
-
从JDk 5.0开始,java提供了更强大的线程同步机制——通过显示定义同步锁对象来实现同步。同步锁使用Lock对象充当。
-
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
-
ReentrantLock类(可重入锁)实现了Lock,他拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
-
一般的书写格式
class A{ private final ReetrantLock lock = new ReetrantLock; public void m(){ lock.lock(); try{ //保证线程安全的代码 }finally{ lock.unlock(); //如果同步代码有异常,要将unlock()写入finally语句块中 } } }
例子
买票问题:
public class Lock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
}
}
class Ticket implements Runnable{
private int ticket = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
lock.lock();
while (true){
if (ticket > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticket--);
}else {
break;
}
}
}finally {
lock.unlock();
}
}
}
运行结果
使用ReentrantLock之后会一次排队抢票。
Lock&synchronized的区别
- Lock是显式的锁(手动开启和关闭锁,别忘记关闭锁),synchronized是隐式锁,出了作用域自动释放。
- Lock只有代码块锁,synchronized有代码块锁和方法锁。
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)。
- 优先使用顺序:
- Lock > 同步代码块(已经进入方法体,分配了相应的资源) > 同步方法(在方法体之外)。
评论区