• 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
    
  • 相关阅读:
    #背包#nssl 1488 上升子序列
    #环#nssl 1487 图
    #分治#JZOJ 4211 送你一颗圣诞树
    #概率,dp#JZOJ 4212 我想大声告诉你
    #并查集#JZOJ 4223 旅游
    #dp#nssl 1478 题
    #对顶堆#nssl 1477 赛
    #线段树,离散#nssl 1476 联
    #折半搜索,状压dp#nssl 1471 Y
    #并查集,线性筛#nssl 1470 X
  • 原文地址:https://www.cnblogs.com/lanqie/p/7614854.html
Copyright © 2020-2023  润新知