第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);
}
}
}