首页 > 应用开发 > Java > Java创建多线程的四种方式
|
|
|
|---|---|
|
1
2
3
4
5
6
|
class
MyThead ``extends
Thread {
@Override
public
void
run() {
System.out.println(Thread.currentThread().getName() + ``": 继承Thread线程啦"``);
}
}
|
|
|
|
|---|---|
| 1 |
new
MyThead().start(); |

|
|
|
|---|---|
|
1
2
3
4
5
|
class
MyRunnable ``implements
Runnable {
public
void
run() {
System.out.println(Thread.currentThread().getName() + ``": 实现Runnable线程啦"``);
}
}
|
|
|
|
|---|---|
| 1 |
new
Thread(``new
MyRunnable()) .start(); |
|
|
|
|---|---|
|
1
2
3
4
5
6
7
8
9
|
class
MyCallable ``implements
Callable<Map<String, String>> {
public
Map<String, String> call() ``throws
Exception {
HashMap<String, String> map = ``new
HashMap<String, String>();
map.put(``"returnCode"``, ``"000000"``);
map.put(``"messgae"``, Thread.currentThread().getName() + ``":Callable创建线程成功"``);
return
map;
}
}
|
|
|
|
|---|---|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
static
void
main(String[] args) {
FutureTask<Map<String, String>> future = ``new
FutureTask(``new
MyCallable());
new
Thread(future).start();
try
{
/**
* get()返回Callable任务里的call()返回值
* get方法是一个阻塞方法,对于task内置了一些任务状态,当任务状态为新建0或者初始化完成的时候1的时候会阻塞
* 需要根据设置的时间阻塞,没有设置时会一直进行阻塞,一直到有结果返回
*/
Map<String, String> resultMap = future.get();
System.out.println(resultMap);
} ``catch
(Exception e) {
e.printStackTrace();
}
}
|
|
|
|
|---|---|
|
1
2
3
4
5
|
public
static
ExecutorService newFixedThreadPool(``int
nThreads) {
return
new
ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new
LinkedBlockingQueue<Runnable>());
}
|
|
|
|
|---|---|
|
1
2
3
4
5
|
public
static
ExecutorService newCachedThreadPool() {
return
new
ThreadPoolExecutor(``0``, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new
SynchronousQueue<Runnable>());
}
|
|
|
|
|---|---|
|
1
2
3
4
5
6
|
public
static
ExecutorService newSingleThreadExecutor() {
return
new
FinalizableDelegatedExecutorService
(``new
ThreadPoolExecutor(``1``, ``1``,
0L, TimeUnit.MILLISECONDS,
new
LinkedBlockingQueue<Runnable>()));
}
|
|
|
|
|---|---|
|
1
2
3
|
public
static
ScheduledExecutorService newScheduledThreadPool(``int
corePoolSize) {
return
new
ScheduledThreadPoolExecutor(corePoolSize);
}
|
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69983799/viewspace-2728766/ ,如需转载,请注明出处,否则将追究法律责任。