this与Thread.currentThread

来源:互联网 发布:云计算和软件工程区别 编辑:程序博客网 时间:2024/06/06 03:17

this指代new TestJoin(),而currentThread()指代new Thread(new TestJoin())


public class TestJoin implements Runnable {    public static void main(String[] sure) throws InterruptedException {        Thread t = new Thread(new TestJoin());        long start = System.currentTimeMillis();        t.start();        t.join(1000);//等待线程t 1000毫秒        System.out.println(System.currentTimeMillis()-start);//打印出时间间隔        System.out.println("Main finished");//打印主线程结束    }    @Override    public void run() {//理解这里为何不用this关键字,this指代new TestJoin(),而currentThread()指代new Thread(new TestJoin())        synchronized (Thread.currentThread()) {            for (int i = 1; i <= 5; i++) {                try {                    TimeUnit.SECONDS.sleep(1);//睡眠5秒,循环是为了方便输出信息                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("睡眠" + i);            }            System.out.println("TestJoin finished");//t线程结束        }    }}


阅读全文
0 0
原创粉丝点击