网站大量收购独家精品文档,联系QQ:2885784924

Java多线程管理分解.ppt

  1. 1、本文档共23页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
第三讲 线程管理 本章目标 线程的优先级: 优先级概述 线程优先级的具体应用 线程同步: 线程同步的目的 线程同步的具体应用 线程死锁: 产生死锁的必要条件与解决方法 wait和notify机制 线程优先级 多线程运行时需要定义线程运行的先后顺序 线程优先级是用数字表示,数字越大线程优先级越高,取值在(1到10)。 默认优先级(为5)。 优先级应用一 public class PriThread { public static void main(String args[ ]) { ThreadA a=new ThreadA(); ThreadB b=new ThreadB(); a.setPriority(2);//设置优先级别,数值越大优先级越高 b.setPriority(3); a.start(); b.start(); } } 优先级应用二 class ThreadA extends Thread { public void run() { System.out.println(我是线程A); } } class ThreadB extends Thread { public void run() { System.out.println(我是线程B); } } 因为在代码段当中我们把线程B的优先级设置高于线程A,所以运行结果先执行线程B的run()方法后再执行线程A的run()方法。 线程优先级的获得 JAVA中获得线程优先级的方法,是通过getPriority()方法来实现的。 public class PriThread { public static void main(String args[ ]) { Thread a=new Thread(); Thread b=new Thread(); int priA=a.getPriority();//获得优先级的方法 int priB=b.getPriority(); System.out.println(priA); System.out.println(priB); } } 线程常量设置优先级 设置优先级也可以用线程常量。 MAX_PRIORITY为最高优先级10; MIN_PRIORITY为最低优先级1; NORM_PRIORITY是默认优先级5。 线程常量设置优先级示例 public class PriConstant { public static void main(String args[ ]) { Thread a=new Thread(); int temp=Thread.MAX_PRIORITY; a.setPriority(temp); //设置此线程优先级最高 System.out.println(a.getPriority()); temp=Thread.MIN_PRIORITY; a.setPriority(temp); //设置此线程优先级最低 System.out.println(a.getPriority()); temp=Thread.NORM_PRIORITY; a.setPriority(temp); //将线程优先级设置为默认 System.out.println(a.getPriority()); } } 线程安全问题 public class Piao { public int num; public Piao(int num){ this.num = num; } public void sell(String name){ if(num=0){ return; } System.out.println(name+卖+num); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } num=num-1; } } 安全问题的解决 Java中嵌套同步是安全的 同步化方法 同步块的方式: void method() { synchronized(this) { // } } 同步方法: synchronized void method() { // } 同步原理 synchronized (object) { // } 钥匙在对象中,而不在代码中。 每个对象有一个钥匙 为了执行synchronized()块,线程需要得到对象中的钥匙。一旦获得了钥匙,对

文档评论(0)

1112111 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档