线程的创建


1.方式一:继承Thread类

  1.1 创建一个继承于Thread类的子类。

  1.2 重写Thread类的run方法。

public class Thread1 extends Thread{
    @Override
    public void run() {
        //遍历100以内的偶数
        for (int i = 0; i < 100; i++) {
                if (i%2==0)
                System.out.println(i);
        }
    }
}

  1.3 创建Thread类子类的对象。

  1.4 通过此对象调用start方法。

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();
    }

    运行效果:

2. 方式二:实现Runnable接口

  2.1 创建一个实现了Runnable接口的类。

  2.2 实现类去实现Runnable接口的run方法。

public class Thread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 ==0)
                System.out.println(i);
        }
    }
}

  2.3 创建实现类的对象。

  2.4 将此对象作为参数传递给Thread类的构造器中,创建Thread类的对象。

  2.5 通过Thread类的对象调用start方法。

    public static void main(String[] args) {
        Thread2 thread2 = new Thread2();
        Thread thread = new Thread(thread2);
        thread.start();
    }

 3. 方式三:实现Callable接口

  3.1 创建一个实现Callable接口的类。

  3.2 实现call方法,将此线程需要的操作声明在call()中。

public class Thread3 implements Callable {
    @Override
    public Object call() throws Exception {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0)
                System.out.println(i);
        }
        return null;
    }
}

  3.3 创建Callable接口实现类的对象。

  3.4 将此Callable接口实现类的对象传递到FutureTask构造器中。

  3.5 将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread类对象,并调用start方法。

    public static void main(String[] args) {
        Thread3 thread3 = new Thread3();
        FutureTask task = new FutureTask(thread3);
        Thread thread = new Thread(task);
        thread.start();
    }

4. 方式四:线程池

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new Thread2());
        executorService.shutdown();