public static void main(String[] args) {
HelloThread th = new HelloThread();
th.setName("HelloThread线程");
th.setPriority(5);
th.start();
for (int i = 0; i < 100; i++) {
Thread.currentThread().setName("main线程");
System.out.println("i="+i+"==线程名=="+Thread.currentThread().getName()+"==优先级 =="+Thread.currentThread().getPriority());
if(i==5){
System.out.println("-----------现在执行的线程是-------"+Thread.currentThread().getName());
Thread.yield();
System.out.println("下面HelloThread线程与main线程都处于就绪状态,抢夺cpu执行权,谁先抢到执行谁");
}
}
}
HelloThread th = new HelloThread();
th.setName("HelloThread线程");
th.setPriority(5);
th.start();
for (int i = 0; i < 100; i++) {
Thread.currentThread().setName("main线程");
System.out.println("i="+i+"==线程名=="+Thread.currentThread().getName()+"==优先级 =="+Thread.currentThread().getPriority());
if(i==5){
System.out.println("-----------现在执行的线程是-------"+Thread.currentThread().getName());
Thread.yield();
System.out.println("下面HelloThread线程与main线程都处于就绪状态,抢夺cpu执行权,谁先抢到执行谁");
}
}
}
public class HelloThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("i="+i+"**当前线程名**"+Thread.currentThread().getName()+"**优先级**"+Thread.currentThread().getPriority());
}
super.run();
}
}
public static void main(String[] args) {
HelloThread th = new HelloThread();
th.setName("HelloThread线程");
th.setPriority(5);
th.start();
for (int i = 0; i < 100; i++) {
Thread.currentThread().setName("main线程");
System.out.println("i="+i+"==线程名=="+Thread.currentThread().getName()+"==优先级=="+Thread.currentThread().getPriority());
if(i==5){
System.out.println("-----------现在执行的线程是-------"+Thread.currentThread().getName());
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下面HelloThread线程执行完,main线程才继续执行");
}
}
}
HelloThread th = new HelloThread();
th.setName("HelloThread线程");
th.setPriority(5);
th.start();
for (int i = 0; i < 100; i++) {
Thread.currentThread().setName("main线程");
System.out.println("i="+i+"==线程名=="+Thread.currentThread().getName()+"==优先级=="+Thread.currentThread().getPriority());
if(i==5){
System.out.println("-----------现在执行的线程是-------"+Thread.currentThread().getName());
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下面HelloThread线程执行完,main线程才继续执行");
}
}
}
1、join()方法
等待调用join方法的线程结束,再继续执行。比如线程A中调用线程B的join()方法,那线程A在threadB.jion()调用过后进入WAITING状态,threadB运行结束后线程A回到RUNNABLE状态继续运行。
2、yield()方法
当前线程让出CPU权限,线程从RUNNING状态进入READY状态。即yield()方法只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行,另外yield()方法只能使同优先级或者高优先级的线程得到执行机会