java创建线程的方式有几种?

Python015

java创建线程的方式有几种?,第1张

java创建线程的方式有三种\x0d\x0a第一种是继承Thread类 实现方法run() 不可以抛异常 无返回值\x0d\x0a第二种是实现Runnable接口 实现方法run() 不可以抛异常 无返回值\x0d\x0a第三种是实现Callable接口,接口中要覆盖的方法是 public call() 注意:此方法可以抛异常,而前两种不能 而且此方法可以有返回值\x0d\x0a\x0d\x0a第三种如何运行呢 Callable接口在util.concurrent包中,由线程池提交\x0d\x0aimport java.util.concurrent.*\x0d\x0aExecutorService e = Executors.newFixedThreadPool(10)参数表示最多可以运行几个线程\x0d\x0ae.submit()这个里面参数传 实现Callable接口那个类的对象

java中实现多线程常用的方法有以下三种:

/**

 * 方法一:继承Thread类,重写run方法

 * 

 * @author qd

 *

 */

public class MyThread extends Thread {

    @Override

    public void run() {

        super.run()

    }

}

/**

 * 方法二:实现Runnable接口,,重写run方法

 * 

 * @author qd

 *

 */

class MyThread1 implements Runnable {

    @Override

    public void run() {

    }

}

/**

 * 方法三:实现Callable<T>接口,重写call方法

 * 优点:可以传参数,有返回值类型(参数与返回值类型一致)

 * 

 * @author qd

 *

 */

class MyThread2 implements Callable<Integer> {

    @Override

    public Integer call() throws Exception {

        return null

    }

}

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网找到很多例子