|
join方法是,用对象名称调用,在一个线程t2中调用另一个线程t1的join方法,线程t2会等待线程t1执行完后在执行 例: - public class Demo extends Thread {
- public static void main(String[] args) {
- final Thread t1 = new Thread() {
- public void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println("t1 : " + i);
- }
- }
- };
- Thread t2 = new Thread() {
- public void run() {
- try {
- // 在另一方法里面只能调用final的局部变量,t1执行完后才会执行t2
- t1.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for (int i = 0; i < 10; i++) {
- System.out.println("t2 : " + i);
- }
- }
- };
- t1.start();
- t2.start();
- // 由于以下方法的线程级别高,所以会先执行
- System.out.println("demo exit");
- }
- }
复制代码
yield,相当与sleep()方法,只是没有指定休眠时间数,而且yield方法只让给相同级别的线程执行,如果没有相同级别的,线程继续运行,不退出。例:- public class Demo01 {
- public static void main(String[] args) {
- Mythread mt = new Mythread("a");
- mt.start();
- Mythread mt2 = new Mythread("b");
- mt2.start();
- }
- }
- class Mythread extends Thread {
- public Mythread(String name) {
- super(name);
- }
- public void run() {
- for (int i = 0; i < 20; i++) {
- // 通过getId()方法,可以取到cpu为该线程分配的long类型的数字编号。程序员不能自己设置线程的id
- System.out.println(getName() + ":" + i + "---id:" + getId());
- // 通过类型调用yield()方法,可以使线程让步:
- Mythread.yield();
- }
- }
- }
复制代码
|