线程的三种实现方式

Java线程的三种实现方式:
大家通常了解的是Thread类与Runnable接口

一、Thread线程
    Thread线程就是覆盖Thread类的run(){}方法
代码例子:

构建自己的线程:

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

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

启动线程:

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



二、Runnable接口线程

   Runnable接口线程的构建就是实现run方法

构建线程:
class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

启动线程:

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


三、Callable接口线程

Callable是比较特殊的线程接口与Runnable的区别是能够返回相关的处理结果一般与
FutureTask组合使用,用task承接返回结果
Callable线程的实现是实现call方法
注意返回类型的控制

构建线程:

public class ComputeValue implements Callable<Integer> {

@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
Thread.sleep(10000);
return 5;
}

}

启动线程:

                ComputeValue callable = new ComputeValue();
FutureTask task = new FutureTask(callable);
Thread thread = new Thread(task);
thread.start();
                System.out.println(task.get());

猜你喜欢

转载自caizhaohua.iteye.com/blog/2215720