实现Runnable接口

public class FirstThread implements Runnable {

    @Override
    public void run() {
        System.out.println("first thread run...");
    }
}

new Thread(new FirstThread().start())

继承Thread类

Thread类本身就是实现的Runnable接口: Thread implements Runnable

public class SecondThread extends Thread {

    @Override
    public void run() {
        System.out.println("second thread run...");
    }
}
new Thread(new SecondThread().start())

实现Callable接口来创建Thread线程

public class ThreeCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int i =0;
        for(;i<100;i++){
            System.out.println(Thread.currentThread().getName()+""+i);
        }
        return i;
    }
}
 public static void main(String[] args) {
        ThreeCallable threeCallable = new ThreeCallable();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(threeCallable);
        new Thread(futureTask).start();
        try {
            System.err.println("futuretask" + futureTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

线程池

import java.util.concurrent.Executors;

/**
 * Created by zhang.gl on 09-11-011.
 * YXV0aG9yOiB6aGFuZ2d1b2xpLmNu
 */
public class ExecutorThread {

    public static void main(String[] args) {
        Executors.newFixedThreadPool(3).execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("newFixedThreadPool" + Thread.currentThread().getName());
            }
        });
    }
}

标签: Java, 线程, thread

添加新评论