java 多线程二

java 多线程一

java 多线程二

java 多线程三

java 多线程四

线程中断:

/**
 * Created by root on 17-9-30.
 */
public class Test4Thread2 {

    public static void main(String[] args) {
        Thread t=new Thread(()->{try {
            System.out.println(Thread.currentThread().getName()+"start");
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName()+"end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }});
        t.start();

        Thread t2=new Thread(()->{try {
            for (int i=0;i<10;i++){
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+">>>"+i);
                if (i==3){
                    t.interrupt();
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }});
        t2.start();

    }
}

 输出:

Thread-0start
Thread-1>>>0
Thread-1>>>1
Thread-1>>>2
Thread-1>>>3
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.xh.alibaba.Test4Thread2.lambda$main$0(Test4Thread2.java:11)
	at java.lang.Thread.run(Thread.java:745)
Thread-1>>>4
Thread-1>>>5
Thread-1>>>6
Thread-1>>>7
Thread-1>>>8
Thread-1>>>9

Process finished with exit code 0

 当线程0在休眠时,线程1打断他,就会报异常。

线程优先级:

/**
 * Created by root on 17-9-30.
 */
public class Test4Thread3 {

    public static void main(String[] args) {
        MyT1 myT1 = new MyT1();
        Thread t2_1 = new Thread(myT1,"myT1_1");
        Thread t2_2 = new Thread(myT1,"myT1_2");
        Thread t2_3 = new Thread(myT1,"myT1_3");
        t2_1.setPriority(1);
        t2_2.setPriority(10);
        t2_3.setPriority(1);
        t2_1.start();
        t2_2.start();
        t2_3.start();
    }

}



class MyT1 implements Runnable {
    int tickets = 10;

    public void run() {
        for (; tickets > 0; ) {
            System.out.println(Thread.currentThread().getName() + ":" + tickets--);
        }
    }
}

 结果:

myT1_2:10
myT1_3:9
myT1_1:7
myT1_2:8
myT1_2:4
myT1_2:3
myT1_2:2
myT1_2:1
myT1_1:5
myT1_3:6

Process finished with exit code 0
原文地址:https://www.cnblogs.com/lanqie/p/7614854.html