多线程的几种常见方式

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class MainTest  {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thread2());
        Thread t3 = new Thread(new Thread3());
        Thread t4 = new Thread(new Thread4());
        FutureTask futureTask5 = new FutureTask(new Thread5());
        Thread t5 = new Thread(futureTask5);
        FutureTask futureTask6 = new FutureTask(new Thread6());
        Thread t6 = new Thread(futureTask6);
            /*t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
            t6.start();*/
        Thread7 thread7 = new Thread7();
        thread7.RunTest();



    }
}

class Thread1 extends Thread {
    public String test = "线程1输出";

    public void SysOut() {
        System.out.println(test);
    }

    @Override
    public void run() {
        SysOut();
    }
}
class Thread2 extends Thread {
    public String test = "线程2输出";

    public void SysOut() {
        System.out.println(test);
    }

    @Override
    public void run() {
        SysOut();
    }
}

class Thread3 implements Runnable {
    public String test = "线程3输出";


    @Override
    public void run() {
        System.out.println(test);
    }
}
class Thread4 implements Runnable {
    public String test = "线程4输出";


    @Override
    public void run() {
        System.out.println(test);
    }
}

class Thread5 implements Callable {
    public String test = "线程5输出";

    public Object SysOut() {
        System.out.println(test);
        return test;
    }
    @Override
    public Object call() throws Exception {
        return this.SysOut();
    }
}
class Thread6 implements Callable {
    public String test = "线程6输出";

    public Object SysOut() {
        return test;
    }
    @Override
    public Object call() throws Exception {
        //System.out.println(test);
        return this.SysOut();
    }
}

class Thread7 {
    public static void RunTest() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        Thread6 thread6 = null;
        List futureList = new ArrayList();
        System.out.println("-->>线程开始"+new Date().toString());
        for (int i=0 ;i<5;i++) {
            thread6 = new Thread6();
            Future f=executorService.submit(thread6);
            futureList.add(f);

        }
        //池技术要记得关闭
        executorService.shutdown();

        for (Future f : futureList) {
            System.out.println("-->>"+f.get().toString());
        }

        System.out.println("-->>线程结束"+new Date().toString());

    }
}

你可能感兴趣的:(多线程)