java有几种实现线程的方式

Python016

java有几种实现线程的方式,第1张

java创建线程的方式有三种

第一种是继承Thread类 实现方法run() 不可以抛异常 无返回值

第二种是实现Runnable接口 实现方法run() 不可以抛异常 无返回值

第三种是实现Callable<T>接口,接口中要覆盖的方法是 public <T>call() 注意:此方法可以抛异常,而前两种不能 而且此方法可以有返回值

第三种如何运行呢 Callable接口在util.concurrent包中,由线程池提交

import java.util.concurrent.*

ExecutorService e = Executors.newFixedThreadPool(10)参数表示最多可以运行几个线程

e.submit()这个里面参数传 实现Callable接口那个类的对象

java中实现一个线程的方法:

基本的是两种:

第一种是继承Tread class:

class PrimeThread extends Thread { long minPrimePrimeThread(long minPrime) { this.minPrime = minPrime} public void run() { // compute primes larger than minPrime . . . } }

在main里:

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

还有就一种是implements Runnable:

public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!")} public static void main(String args[]) { (new Thread(new HelloRunnable())).start()}}

同样用 xxx.start() 可以运行这个线程

这是基本的,还有就是管理一群线程(threads pool),可以用executor以及executor service, 以上信息都可以在oracle网找到很多例子