多线程2
11.1线程优先级的设置
在同个程序中每个钱程都具有自己的优先级别,规程的优先级越高,获得CPU几行的机会就越大反之,找样的化济仅越低获得 CPU执行的机会就越小,规程的优先级可以用110的数字来表示 ,数字以大 ,表示议代程的代先级品高,设置线程的优先极是控制线程量否优先执行的有效方法,Thread 类中提供了3个用来表示律先级的静态常量,具体风表1-1,
静态常量名段 说明
statie int MAL PRIORITY 知星具有的最高优先级,值为10
state int MIN PRIORITY 规程具有的最低优先级,值为1
statie int NORML PRIORITY 规程具有的默认优先级,值为5
表线程优先级的常量,设置线程的优先级可以通过Thread类中的setPriority(newPriority)方法来实现,没方法中的参数newPriority代表规程优先级别值,其取值为1~10的整数,下过一个示例来演示线程优先级的设置,
示例
public class PriorityTest (
public static vold main(String[) args) (
Thread t1。new Thread(new MyPrtorty(),"优先级高的");//创建两条规程Thread t2 new Thread(new MyPriority(),"优先级低的");t1.setPriority(10); 1/设置线程的优先级剧t2.setPriority(1);tl.start()://启动线程t2.start();
class MPriority implements Runnablef
public void run() {
for(int 1=0;i<10;i++)(
//打印线程的名称与值
System.out.println(Thread.currentThread().getName()+"正在打印:"+i);}
}
}
多线程的通讯
public class ProducerCustomerTest { public static void main(String[] args) { // TODO Auto-generated method stub LinkTest11 l=new LinkTest11(); Thread t1 = new Thread(new producer(l)); Thread t2 = new Thread(new Customer(l)); t1.start(); t2.start(); } } class LinkTest11{ int num; boolean flag=false; public synchronized void setNum(int num){ if(flag){ System.out.println("A生产者说有馒头了,我得睡一会儿调用了wait()方法打开锁"); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.num =num; System.out.print("A生产者生产了第"+num+"个馒头"); flag=true; System.out.println("A说赶紧起来吃馒头了,叫醒B消费者"); this.notify(); } public synchronized void getNum(){ if(!flag){ System.out.println("B消费者说吃的太快没有馒头了,我得睡一会儿调用了wait()方法打开锁"); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("B生产者生产了第"+num+"个馒头"); flag=false; System.out.println("B说赶紧起来吃馒头了,叫醒B消费者"); this.notify(); } } class producer implements Runnable{ LinkTest11 l; public producer( LinkTest11 l) { this.l=l; } @Override public void run() { for(int i=1;i<=10;i++){ l.setNum(i); } System.out.println("A生产者下班了"); } } class Customer implements Runnable { LinkTest11 l ; Customer(LinkTest11 l){ this.l = l; } @Override public void run() { // TODO Auto-generated method stub for(int i=1;i<=10;i++){ l.getNum(); } System.out.println("B生产者下班了"); } }