【JavaSE】创建线程

52 阅读1分钟

方法一: 继承Thread类


class myThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i ++){
            System.out.println(i);
        }

    }
}
public class ThreadTest {
    public static void main(String[] args) {

        //方式一:
        myThread myThread = new myThread();
        myThread.start();

        //方式二:因为myThread这个类创建出来就使用了一次,就没在用了,可以考虑匿名方式
        //创建Thread类的匿名子类的对象。。
        //子类继承Thread 重写run方法
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 10; i ++){
                    System.out.println(i);
                }

            }


        }.start();


    }

}

方法二:实现Runable接口

package com.yingzhang.java;


public class ThreadTest1 {
    public static void main(String[] args) {
        MThread thread1 = new MThread();
        new Thread(thread1).start();

        new Thread(thread1).start();
    }

}

class MThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "数值为" + i);

        }

    }
}

方法三:实现callable接口

package com.yingzhang.java;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class ThreadTest2 {
    public static void main(String[] args) {

        Mthread1 mthread = new Mthread1();
        //FutureTask类也实现了runable接口。
        FutureTask task = new FutureTask(mthread);
        new Thread(task).start();

        try {
            Object o = task.get();
            System.out.println("总和为" + o);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }



    }
}

class Mthread1 implements Callable {

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            sum += i;


        }
        return sum;
    }
}

方法四:使用线程池

package com.yingzhang.java;

import java.util.concurrent.*;

public class ThreadTest4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(()->{
            for (int i = 0; i < 5; i++) {
                System.out.println(i);

            }

        });  //适用于runable
        Future future = executorService.submit(()->{
            int sum = 0;
            for (int i = 0; i < 10; i++) {
                sum += i;

            }
            return sum;
        });//适用于callable
        System.out.println("call的返回" + future.get());

    }
}