Java三种线程创建调用方式-Thread、Runnable与Callable

继承类Thread

创建方式:

public class ThreadExtendsThread extends Thread {
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) { }
        // 输出当前进程名称
        System.err.println("ThreadExtendsThread : " 
            + Thread.currentThread().getName() 
            + " : " + System.currentTimeMillis());
    }
}

调用代码:

new ThreadExtendsThread().start();

实现接口Runnable

创建方式:

public class ThreadImplRunnable implements Runnable {
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) { }
        // 输出当前进程名称
        System.err.println("ThreadExtendsThread : " 
                + Thread.currentThread().getName() 
                + " : " + System.currentTimeMillis());
    }
}

调用代码:

new Thread(new ThreadImplRunnable()).start();

实现接口Callable

创建方式:

public class ThreadImplCallable implements Callable<String> {
    public String call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) { }
        // 输出当前进程名称
        System.err.println("ThreadImplCallable : " 
                + Thread.currentThread().getName() 
                + " : " + System.currentTimeMillis());
        return Thread.currentThread().getName();
    }
}

调用代码:

FutureTask<String> futureTask = new FutureTask<String>(new ThreadImplCallable());
futureTask.run();
try {
    System.err.println(futureTask.get(60000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
上一篇:Annotation-自定义注解入门


下一篇:Clickhouse-Java使用JDBC连接大批量导入(本地文件2表)