Java多线程管理分析.ppt

第三讲 线程管理 本章目标 线程的优先级: 优先级概述 线程优先级的具体应用 线程同步: 线程同步的目的 线程同步的具体应用 线程死锁: 产生死锁的必要条件与解决方法 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)

1亿VIP精品文档

相关文档