您的位置:首页 > 编程语言 > Java开发

java实现多线程

2016-06-06 21:16 393 查看

使用线程池方法

java通过Executors提供四种线程池:分别为 newCachedThreadPool; newFixedThreadPool; newScheduledThreadPool; newSingleThreadExecutorpackage test;

优点:

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

for (int i = 0; i < 10; i++) {

final int index = i;

fixedThreadPool.execute(new Runnable() {

public void run() {

try {

System.out.println(index);

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

}

}

}

}

因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

创建一个线程:

1、通过实现Runnable接口

执行一个方法:

public void run()


2、通过继承Thread类本身

Thread(Runnable threadOb,String threadName);


这里,threadOb 是一个实现Runnable 接口的类的实例,并且 threadName指定新线程的名字。

新线程创建之后,你调用它的start()方法它才会运行。
void start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: