java 多线程 二、

加入线程   相当于插队
* join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续。
* join(int), 可以等待指定的毫秒之后继续。

    /**
     * @param args
     * join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续
     */
    public static void main(String[] args) {
        final Thread t1 = new Thread() {
            public void run() {
                for(int i = 0; i < 10; i++) {
                    System.out.println(getName() + "...aaaaaaaaaaaaa");
                }
            }
        };
        
        Thread t2 = new Thread() {
            public void run() {
                for(int i = 0; i < 10; i++) {
                    if(i == 2) {
                        try {
                            //t1.join();
                            t1.join(1);                    //插队指定的时间,过了指定时间后,两条线程交替执行
                        } catch (InterruptedException e) {
                            
                            e.printStackTrace();
                        }
                    }
                    System.out.println(getName() + "...bb");
                }
            }
        };
        
        t1.start();
        t2.start();
    }


礼让线程
* yield让出cpu

public class Demo6_Yield {

    /**
     * yield让出cpu礼让线程
     */
    public static void main(String[] args) {
        new MyThread().start();
        new MyThread().start();
    }

}

class MyThread extends Thread {
    public void run() {
        for(int i = 1; i <= 1000; i++) {
            if(i % 10 == 0) {
                Thread.yield();                        //让出CPU
            }
            System.out.println(getName() + "..." + i);
        }
    }
}

设置线程的优先级
* setPriority()设置线程的优先级

    /**
     * @param args
     */
    public static void main(String[] args) {
        Thread t1 = new Thread(){
            public void run() {
                for(int i = 0; i < 100; i++) {
                    System.out.println(getName() + "...aaaaaaaaa" );
                }
            }
        };
        
        Thread t2 = new Thread(){
            public void run() {
                for(int i = 0; i < 100; i++) {
                    System.out.println(getName() + "...bb" );
                }
            }
        };
        
        //t1.setPriority(10);                    设置最大优先级
        //t2.setPriority(1);
        
        t1.setPriority(Thread.MIN_PRIORITY);        //设置最小的线程优先级
        t2.setPriority(Thread.MAX_PRIORITY);        //设置最大的线程优先级
        
        t1.start();
        t2.start();
    }

}
原文地址:https://www.cnblogs.com/yimian/p/6564635.html