第09章_线程Join_Yield_Priority

Join 合并线程



public class Test20180528{
public static void main(String args[]){
My s = new My();                                \\new一个新的并行线程对象
s.start();                                                \\并行线程开始
try{s.join();                                            \\合并并行线程,此时main方法主线程等待子线程执行完毕后再执行主线程
}catch (InterruptedException e){
}
for (int i = 1;i <=10 ;i++ ){
System.out.println("运行main方法");
}
}
}


class My extends Thread{                                                                \\定义子线程类
public void run(){
for (int i = 0;i <= 10 ;i++ ){
System.out.println(" i am");
try{
sleep(1000);
}catch (InterruptedException e){
System.out.println("出错");
}


}
}

}




yield();

出让优先级

public class Test20180528001{
public static void main(String args[]){
My s1 = new My("s1");                     \\new 两个子线程对象,并行执行,当其中一个子线程循环次数达到10时                                                                                     将让出CPU优先权,让其他线程有限执行
My s2 = new My("s2");
s1.start(); s2.start();
}
}


class My extends Thread{                                                                        \\创建子线程类
My (String s){
super(s);
}
public void run(){
for (int i = 0;i <= 10 ;i++ ){
System.out.println("Hello "+getName());

if (i%10==0){

                        yield();                                                                              \\让出优先权语句

}
}
}

}


增加优先级     setPriority(Thread.NORM_PRIORITY + 5);


public class Test20180528001{
public static void main(String args[]){
Thread  s1 = new Thread(new My());
Thread s2 = new Thread(new My1());
s2.setPriority(Thread.NORM_PRIORITY + 5);                    \\增加优先级5级  一共10级 初始化5级
s1.start(); s2.start();

}
}


class My implements Runnable{


public void run(){
for (int i = 0;i <= 100 ;i++ ){
System.out.println("----------"+i);
}
}
}


class My1 implements Runnable{


public void run(){
for (int i = 0;i <= 100 ;i++ ){
System.out.println("=============="+i);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值