Java——线程的加入

来源:互联网 发布:数据库触发器 编辑:程序博客网 时间:2024/06/14 17:41
//join():加入运行class Test implements Runnable{    public void run(){        for(int i=1;i<=10;i++){            System.out.println(Thread.currentThread().getName()+"--->"+i);        }    }}class Demo{    public static void main(String[] args) throws InterruptedException{        Test test = new Test();        Thread t1 = new Thread(test);        Thread t2 = new Thread(test);        t1.start();//t1 start之后不一定能抢到CPU        //写在这里,加入下面这句话之后,这时只有主线程和t1线程,所以主线程会等待t1线程全部执行完再执行        //t1.join();//让t1线程加入线程,如果没有这句话,t1线程不一定能得到CPU        t2.start();        t1.join();//写在这里,这时有主线程和t1,t2线程,主线程会等待t1线程执行完,t2线程不会让着t1        //join只有主线程会让着他        for(int i=1;i<=10;i++){            System.out.println(Thread.currentThread().getName()+"--->"+i);        }    }}
原创粉丝点击