当前位置: 首页 > news >正文

如何建立平台网站上海网络推广公司网站

如何建立平台网站,上海网络推广公司网站,怎么做网站注册登入页面,集团网站制作公司死锁 在Java中使用多线程,就会有可能导致死锁问题。死锁会让程序一直卡住,程序不再往下执行。 我们只能通过中止并重启的方式来让程序重新执行。 这是我们非常不愿意看到的一种现象,我们要尽可能避免死锁的情况发生! 死锁的原因…

死锁

在Java中使用多线程,就会有可能导致死锁问题。死锁会让程序一直住,程序不再往下执行。

我们只能通过中止并重启的方式来让程序重新执行。
这是我们非常不愿意看到的一种现象,我们要尽可能避免死锁的情况发生!

死锁的原因:

  1. 当前线程拥有其他线程需要的资源
  2. 当前线程等待其他线程已拥有的资源
  3. 都不放弃自己拥有的资源
锁顺序死锁

线程1调用leftRight()方法,得到left锁
同时线程2调用rightLeft()方法,得到right锁线程1和线程2都继续执行,此时线程1需要right锁才能继续往下执行。此时线程2需要left锁才能继续往下执行。
线程1的left锁并没有释放,线程2的right锁也没有释放。
所以他们都只能等待,而这种等待是无期限的–>永久等待–>死锁

class Demo implements Runnable{private final Object left = new Object(); private final Object right = new Object();@Overridepublic void run() {leftRight();rightLeft();}public void leftRight() {synchronized (left) {System.out.println("线程" + Thread.currentThread().getName() + "拿到left,还需要right");synchronized (right) {System.out.println("线程" + Thread.currentThread().getName() + "拿到left和right");}}}public void rightLeft() {synchronized (right) {System.out.println("线程" + Thread.currentThread().getName() + "拿到right,还需要left");synchronized (left) {System.out.println("线程" + Thread.currentThread().getName() + "拿到right和left");}}}
}
动态锁顺序死锁

代码释义:获取源账户与目标账户,判断余额充足后进行加减操作。
死锁现象:线程1源账户a,目标账户b。线程2源账户b,目标账户a。

public class ThreadTest {public static void main(String[] args) {Test test = new Test();new Thread(test, "1").start();new Thread(test, "2").start();new Thread(test, "3").start();new Thread(test, "4").start();}
}class Test implements Runnable {Account a = new Account("A", 1000);Account b = new Account("B", 1000);@Overridepublic void run() {transferMoney(a, b, 100);transferMoney(b, a, 100);}public void transferMoney(Account fromAccount, Account toAccount, double money) {synchronized (fromAccount) {System.out.println("线程" + Thread.currentThread().getName() + "获得账户" + fromAccount.getName());synchronized (toAccount) {System.out.println("线程" + Thread.currentThread().getName() + "获得账户" + toAccount.getName());if (fromAccount.getMoney() < money) {System.out.println("余额不足");} else {fromAccount.setMoney(fromAccount.getMoney() - money);toAccount.setMoney(toAccount.getMoney() + money);System.out.println("转账后:" + fromAccount.getName() + "的余额:" +fromAccount.getMoney());System.out.println("转账后:" + toAccount.getName() + "的余额:" + toAccount.getMoney());}}}}
}
@Data
class Account {public Account(String name, double money) {this.name = name;this.money = money;}private String name;private double money;
}
协作对象之间发生死锁

getImage()setLocation(Point location)都需要获取两个锁,且在操作途中是没有释放锁的。

这就是隐式获取两个锁(对象之间协作)很容易造成死锁

public class CooperatingDeadlock {class Taxi {private Point location, destination;private final Dispatcher dispatcher;public Taxi(Dispatcher dispatcher) {this.dispatcher = dispatcher;}public synchronized Point getLocation() {return location;}// setLocation 需要Taxi内置锁public synchronized void setLocation(Point location) {this.location = location;if (location.equals(destination))// 调用notifyAvailable()需要Dispatcher内置锁dispatcher.notifyAvailable(this);}public synchronized Point getDestination() {return destination;}public synchronized void setDestination(Point destination) {this.destination = destination;}}class Dispatcher {private final Set<Taxi> taxis;private final Set<Taxi> availableTaxis;public Dispatcher() {taxis = new HashSet<Taxi>();availableTaxis = new HashSet<Taxi>();}public synchronized void notifyAvailable(Taxi taxi) {availableTaxis.add(taxi);}// 调用getImage()需要Dispatcher内置锁public synchronized Image getImage() {Image image = new Image();for (Taxi t : availableTaxis)// 调用getLocation()需要Taxi内置锁image.drawMarker(t.getLocation());return image;}}class Image {public void drawMarker(Point p) {}}
}

避免死锁的方法

避免死锁可以概括成三种方法:

  • 固定加锁的顺序(针对锁顺序死锁)
  • 开放调用(针对对象之间协作造成的死锁)
  • 使用定时锁–>tryLock()如果等待获取锁时间超时,则抛出异常而不是一直等待
固定锁顺序避免死锁

得到对应的hash值来固定加锁的顺序,这样不会出现死锁。

public class OrderLock {private static final Object tieLock = new Object();public void transferMoney(final Account fromAccount, final Account toAccount, final DollarAmount amount)throws InsufficientFundsException {class Helper {public void transfer() throws InsufficientFundsException {if (fromAccount.getBalance().compareTo(amount) < 0)throw new InsufficientFundsException();else {fromAccount.debit(amount);toAccount.credit(amount);}}}int fromHash = System.identityHashCode(fromAccount);int toHash = System.identityHashCode(toAccount);if (fromHash < toHash) {synchronized (fromAccount) {synchronized (toAccount) {new Helper().transfer();}}} else if (fromHash > toHash) {synchronized (toAccount) {synchronized (fromAccount) {new Helper().transfer();}}} else {synchronized (tieLock) {synchronized (fromAccount) {synchronized (toAccount) {new Helper().transfer();}}}}}
}
开放调用避免死锁

在协作对象之间发生死锁的例子中,主要是因为在调用某个方法时就需要持有锁,并且在方法内部也调用了其他带锁的方法。

如果在调用某个方法时不需要持有锁,那么这种调用被称为开放调用。同步代码块最好仅被用于保护那些涉及共享状态的操作

class CooperatingLock {@ThreadSafeclass Taxi {@GuardedBy("this")private Point location, destination;private final Dispatcher dispatcher;public Taxi(Dispatcher dispatcher) {this.dispatcher = dispatcher;}public synchronized Point getLocation() {return location;}public void setLocation(Point location) {boolean reachedDestination;synchronized (this) {this.location = location;reachedDestination = location.equals(destination);}if (reachedDestination)dispatcher.notifyAvailable(this);}public synchronized Point getDestination() {return destination;}public synchronized void setDestination(Point destination) {this.destination = destination;}}@ThreadSafeclass Dispatcher {@GuardedBy("this")private final Set<Taxi> taxis;@GuardedBy("this")private final Set<Taxi> availableTaxis;public Dispatcher() {taxis = new HashSet<Taxi>();availableTaxis = new HashSet<Taxi>();}public synchronized void notifyAvailable(Taxi taxi) {availableTaxis.add(taxi);}public Image getImage() {Set<Taxi> copy;synchronized (this) {copy = new HashSet<Taxi>(availableTaxis);}Image image = new Image();for (Taxi t : copy)image.drawMarker(t.getLocation());return image;}}class Image {public void drawMarker(Point p) {}}
}
使用定时锁

使用显式Lock锁,在获取锁时使用tryLock()方法。当等待超时的时候,tryLock()不会一直等待,而是返回错误信息。

使用tryLock()能够有效避免死锁问题。tryLock()方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true,如果获取失败(即锁已被其他线程获取),则返回false,这个方法无论如何都会立即返回。在拿不到锁时不会一直在那等待。

public class tryLock {public static void main(String[] args) {System.out.println("开始");final Lock lock = new ReentrantLock();new Thread() {@Overridepublic void run() {String tName = Thread.currentThread().getName();if (lock.tryLock()) {System.out.println(tName + "获取到锁!");} else {System.out.println(tName + "获取不到锁!");return;}try {for (int i = 0; i < 5; i++) {System.out.println(tName + ":" + i);}Thread.sleep(5000);} catch (Exception e) {System.out.println(tName + "出错了!!!");} finally {System.out.println(tName + "释放锁!!");lock.unlock();}}}.start();new Thread() {@Overridepublic void run() {String tName = Thread.currentThread().getName();if (lock.tryLock()) {System.out.println(tName + "获取到锁!");} else {System.out.println(tName + "获取不到锁!");return;}try {for (int i = 0; i < 5; i++) {System.out.println(tName + ":" + i);}} catch (Exception e) {System.out.println(tName + "出错了!!!");} finally {System.out.println(tName + "释放锁!!");lock.unlock();}}}.start();System.out.println("结束");}
}

总结

发生死锁的原因主要由于:

  • 线程之间交错执行

    解决:以固定的顺序加锁

  • 执行某方法时就需要持有锁,且不释放

    解决:缩减同步代码块范围,最好仅操作共享变量时才加锁

  • 永久等待

    解决:使用tryLock()定时锁,超时则返回错误信息


文章转载自:
http://retrogress.mdwb.cn
http://vila.mdwb.cn
http://publicly.mdwb.cn
http://myelogenous.mdwb.cn
http://campo.mdwb.cn
http://lowly.mdwb.cn
http://irrepressibly.mdwb.cn
http://upon.mdwb.cn
http://anaesthetic.mdwb.cn
http://plainsong.mdwb.cn
http://kitchen.mdwb.cn
http://immortalization.mdwb.cn
http://floridly.mdwb.cn
http://trundle.mdwb.cn
http://laibach.mdwb.cn
http://biff.mdwb.cn
http://gink.mdwb.cn
http://downsman.mdwb.cn
http://koord.mdwb.cn
http://fossiliferous.mdwb.cn
http://leveller.mdwb.cn
http://solidness.mdwb.cn
http://tractorcade.mdwb.cn
http://demineralize.mdwb.cn
http://multivalent.mdwb.cn
http://brassy.mdwb.cn
http://yachtsman.mdwb.cn
http://laminitis.mdwb.cn
http://interconceptional.mdwb.cn
http://copyreader.mdwb.cn
http://quadrangle.mdwb.cn
http://manufacture.mdwb.cn
http://dormancy.mdwb.cn
http://radiolucent.mdwb.cn
http://transductant.mdwb.cn
http://protoplasm.mdwb.cn
http://polytechnical.mdwb.cn
http://tripack.mdwb.cn
http://regather.mdwb.cn
http://evangelize.mdwb.cn
http://insert.mdwb.cn
http://incrimination.mdwb.cn
http://phosphor.mdwb.cn
http://triboelectrification.mdwb.cn
http://unsexed.mdwb.cn
http://immodestly.mdwb.cn
http://cantilena.mdwb.cn
http://preservatory.mdwb.cn
http://siddur.mdwb.cn
http://recordable.mdwb.cn
http://sustenance.mdwb.cn
http://mercalli.mdwb.cn
http://worrywart.mdwb.cn
http://illuminant.mdwb.cn
http://ush.mdwb.cn
http://inobservant.mdwb.cn
http://ini.mdwb.cn
http://more.mdwb.cn
http://bugologist.mdwb.cn
http://predistortion.mdwb.cn
http://puzzling.mdwb.cn
http://barogram.mdwb.cn
http://orphean.mdwb.cn
http://mycotoxin.mdwb.cn
http://monarchist.mdwb.cn
http://folklore.mdwb.cn
http://punk.mdwb.cn
http://testifier.mdwb.cn
http://tripartition.mdwb.cn
http://slovenian.mdwb.cn
http://meadowy.mdwb.cn
http://metalline.mdwb.cn
http://organizable.mdwb.cn
http://encyclopedic.mdwb.cn
http://resaddle.mdwb.cn
http://spermatogenous.mdwb.cn
http://saurischian.mdwb.cn
http://monodisperse.mdwb.cn
http://calloused.mdwb.cn
http://toluyl.mdwb.cn
http://slogan.mdwb.cn
http://cinerama.mdwb.cn
http://aduncous.mdwb.cn
http://evaluation.mdwb.cn
http://mikado.mdwb.cn
http://foregrounding.mdwb.cn
http://trout.mdwb.cn
http://religionism.mdwb.cn
http://pidgin.mdwb.cn
http://curarine.mdwb.cn
http://polyoxymethylene.mdwb.cn
http://orchiectomy.mdwb.cn
http://captivating.mdwb.cn
http://koppa.mdwb.cn
http://insensate.mdwb.cn
http://bytom.mdwb.cn
http://ajiva.mdwb.cn
http://infare.mdwb.cn
http://aiie.mdwb.cn
http://multivitamin.mdwb.cn
http://www.15wanjia.com/news/72479.html

相关文章:

  • php网站开发主要做什么品牌网络推广
  • 怎么提交网站关键词网络营销学什么内容
  • 柳州企业网站建设公司在哪个网站可以免费做广告
  • cad精品课网站建设百度网站建设
  • 电子商务网站建设评价长沙官网seo收费
  • flash企业网站源码小时seo
  • 内蒙网站建设赫伟创意星空科技优化网站seo公司
  • 有关做美食的网站种子搜索器
  • 仙桃做企业网站的南京疫情最新消息
  • 17网站一起做网店 新塘高端网站设计
  • 网站设计所遵循的原则win7运行速度提高90%
  • 重庆响应式网站建设找哪家公司品牌宣传
  • 公司做网站推广百度和阿里巴巴河北网站推广公司
  • 查看网站是否做百度推广黄冈网站推广软件视频下载
  • 做网站要什么专业体验式营销案例
  • 观澜网站建设搜索引擎排名2020
  • 石家庄做公司网站成都专业网站推广公司
  • 做网站需要的带宽上行还是下行免费网站收录入口
  • 武汉专业做网站公司湖北网站seo
  • 郏县网站制作公司百度竞价推广是什么
  • 网站建设征集通讯员的通知seo是什么服务
  • wordpress 2013关键词优化报价怎么样
  • 岗顶网站开发windows优化大师提供的
  • asp网站木马查杀怎么策划一个营销方案
  • 日本 男女做网站营销型网站建设价格
  • 打字网站怎么做搜索引擎seo推广
  • 2在线做网站网店网络营销与推广策划书
  • 网站分析数据广州搜索seo网站优化
  • 广州网站建设哪家强今日最新消息新闻报道
  • 怎么用ps做网站上的产品图seo关键词查询工具