实现线程的四种方法-Java Thread

实现线程的四种方法

1.  实现java.lang.Runnable接口

public class RunableDemo {

    public static void main(String[] args) {
        MyThread mth = new MyThread();
        new Thread(mth).start();
    }
}

class MyThread implements Runnable{
    public void run() {
        System.out.println("This is a thread implemented by Runnable Interface.");
    }   
}


2.  继承java.lang.Thread类

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread mth = new MyThread();
        mth.start();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("This is a thread implemented by Thread Class.");
    }
}


3. 实现java.util.concurrent.Callable接口通过java.util.concurrent.FutureTask包装器来创建Thread线程

public class CallableDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException {       
        MyThread mt = new MyThread();
        FutureTask<Integer> result = new FutureTask<Integer>(mt);
        new Thread(result).start();
        System.out.println(result.get());
    }
}

class MyThread implements Callable<Integer> {

    public Integer call() throws Exception {
        int sum=0;
        for(int i=0; i<10; i++){
            sum+=i;
        }
        return sum;
    }
}

4. 使用java.util.concurrent.ExecutorService、java.util.concurrent.Callable、java.util.concurrent.Future实现有返回结果的线程池

public class ThreadPoolDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        int taskSize = 5;
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);       
        List<Future<Integer>> list = new ArrayList<Future<Integer>>();
        for (int i = 0; i < taskSize; i++) {  
            Callable<Integer> c = new MyThread();  
            Future<Integer> f = pool.submit(c);  
            list.add(f);  
        }
        pool.shutdown();
        for (Future<Integer> f : list) {  
            System.out.println(f.get());  
        }
    }

}

class MyThread implements Callable<Integer> {

    public Integer call() throws Exception {
        int sum=0;
        for(int i=0; i<10; i++){
            sum+=i;
        }
        return sum;
    }
}


猜你喜欢

转载自blog.csdn.net/u014010512/article/details/78486422