JavaSE+Thread

来源:互联网 发布:sql replace 替换空格 编辑:程序博客网 时间:2024/06/06 20:42

publicclass CurrentThread {

    publicstaticvoid print(){

       for (int i=0;i<100;i++){

           System.out.print(i+";");

           try {

             System.out.print(Thread.currentThread().getName());

               Thread.sleep(2000);

                System.out.println();

               } catch (NumberFormatException e) {

               //TODOAuto-generated catch block

               e.printStackTrace();

               } catch (InterruptedException e) {

               //TODOAuto-generated catch block

               e.printStackTrace();

               }

           System.out.print(i+3+"+");

       }

    }

    //

    publicstaticvoid main(String[] args) {

       // TODOAuto-generated method stub

       new Thread() {

           publicvoid run() {

             //Thread-0

               CurrentThread.print();

           }

       }.start();

       //main Thread

//       CurrentThread.print();

    }

}

1.1个延迟的功能,这里用Thread.sleep()做测试,原本以为Thread.sleep()只是能用到线程里,但我将主方法里的线程注释掉,直接使用CurrentThread.print();还是会延迟2秒打印,当时的2点疑问在此分享解答:

1.当主方法的线程不注释掉,调用CurrentThread.print();,Thread.sleep()里的线程是指哪个线程?

2.当主方法的线程注释掉,调用CurrentThread.print();,为何还会跟没注释掉1?

1.System.out.print(Thread.currentThread().getName());会告诉你原因:

1.new Thread()里的执行的是新new出来的Thread-0;

2.主方法里直接运行的是main线程执行的;

1.Object.wait()做延时处理源码展示:

publicclass WaitimplementsRunnable{

    private Objectobject =new Object();

    @Override

    publicvoid run() {

       // TODOAuto-generated method stub

       try {

           synchronized (object) {

               for (int i = 0; i < 100; i++) {

                   System.out.print(i+"+");

                   object.wait(2*1000);

                   System.out.print(i + 3+";");

                   object.notifyAll();

                   System.out.println();

               }

           }

       } catch (InterruptedException e) {

           e.printStackTrace();

           return;

       }

    }

    //

    publicstaticvoid main(String args[]) {

       ExecutorService executorService =Executors.newFixedThreadPool(1);

       Wait wait = new Wait();

       executorService.execute(wait);

       executorService.shutdown();

       while (!executorService.isTerminated()) {

       }

    }

}

0 0
原创粉丝点击