第三讲 线程管理 本章目标 线程的优先级: 优先级概述 线程优先级的具体应用 线程同步: 线程同步的目的 线程同步的具体应用 线程死锁: 产生死锁的必要条件与解决方法 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()块,线程需要得到对象中的钥匙。一旦获得了钥匙,对
您可能关注的文档
最近下载
- HAIER 海尔 海尔Haier冰箱 BCD-649WE 说明书.pdf
- 信息安全管理平台构建与企业安全大数据战略.docx VIP
- 公共机构节水管理规范.doc VIP
- 如何找回误删微信好友,微信好友一键恢复.doc VIP
- 2012韩山师范学院专升本插班生考试《数据结构》试卷.pdf VIP
- Dragons: Riders of Berk《驯龙记:伯克岛的龙骑手(2012)》第一季第六集完整中英文对照剧本.docx VIP
- 供电设备、供水设备运行维护管理方案.pdf VIP
- 股票操作手册.pdf VIP
- 大数据时代企业管理会计问题及对策.docx VIP
- 大数据对企业管理的影响.doc VIP
原创力文档

文档评论(0)