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