Java中创建线程的三种方法

1.将类声明为 Thread 的子类,该子类应重写 Thread 类的 run 方法

class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             //线程中要执行的代码
              . . .
         }
     }

创建并启动一个线程

 PrimeThread p = new PrimeThread(143);
     p.start();

2.实现 Runnable 接口的类,实现 run 方法

class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // 线程中要执行的代码
              . . .
         }
     }

创建并启动一个线程:

PrimeRun p = new PrimeRun(143);
 new Thread(p).start();

3.使用Callable和Future创建线程

call()方法将作为线程执行体,并且有返回值,调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。

public class Test implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        int count =0;
        for(int i=0;i<=10;i++){
            count=count+i;
        }
        return count;   
    }
}

创建并启动一个线程:

Test test=new ThreadTest();
FutureTask<Integer> thread = new FutureTask<>(test);
new Thread(thread,"有返回值的线程").start();  
System.out.println(thread.get());

猜你喜欢

转载自blog.csdn.net/dc_space/article/details/81159027
今日推荐