线程中断:
/** * 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-0startThread-1>>>0Thread-1>>>1Thread-1>>>2Thread-1>>>3java.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>>>4Thread-1>>>5Thread-1>>>6Thread-1>>>7Thread-1>>>8Thread-1>>>9Process 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:10myT1_3:9myT1_1:7myT1_2:8myT1_2:4myT1_2:3myT1_2:2myT1_2:1myT1_1:5myT1_3:6Process finished with exit code 0