匿名内部类实现多线程

        System.out.println("MAIN start.." + Thread.currentThread().getName());
        new Thread(){
            public void run(){
                System.out.println("【extends thread】主线程名字:" + super.getName());
                System.out.println("【extends thread】主线程名字:" + this.getName());
                System.out.println("【extends thread】当前线程名字:" + Thread.currentThread().getName());
            }
        }.start();

        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("【Runnable】当前线程名字:" + Thread.currentThread().getName());
            }
        }).start();


        //TODO Callable的匿名内部类,必须使用FutureTask包装。需要注意的是,Callable返回void,V必须大写
        new Thread(new FutureTask<Void>(new Callable<Void>(){

            @Override
            public Void call() throws Exception {
                Integer i = 0;
                i++;
                System.out.println("【Callable】 i=" + i);
                System.out.println("【Callable】当前线程名字:" + Thread.currentThread().getName());
                return null;
            }
        })).start();

    System.out.println("MAIN end.." + Thread.currentThread().getName());

测试结果:

MAIN start..main
【extends thread】主线程名字:Thread-0
【extends thread】主线程名字:Thread-0
【extends thread】当前线程名字:Thread-0
MAIN end..main
【Runnable】当前线程名字:Thread-1
【Callable】 i=1
【Callable】当前线程名字:Thread-2

猜你喜欢

转载自blog.csdn.net/qq_38384102/article/details/83782056