要求调用尽可能多的线程执行入队列和出队列任务,希望线程名是不同的
package com.thread;
/**
- @author liuchj
- @version 1.0
- @className MyThreadTest
- @description //TODO
- @date 2019/5/29 **/
import java.util.Queue;
import java.util.concurrent.*;
public class MyThreadTest {
public static void main(String[] args) {
MyThreadTest mtt = new MyThreadTest();
mtt.beginExe();
}
public void beginExe() {
//线程池方式
ExecutorService executor = new ThreadPoolExecutor(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
executor.submit(new MyThreadTest.InnerThread());
}
/**
* 线程:执行入队列、出队列任务的线程
*/
public class InnerThread implements Runnable {
/**
* 线程安全的队列
*/
final Queue<String> queue = new ConcurrentLinkedQueue<String>();
@Override
public void run() {
//入队列
for (int i = 0; i < 9; i++) {
queue.add("task" + i + "" + i);
}
//出队列
while (queue.size() > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = queue.poll();
if (value != "" && null != value) {
System.out.println(Thread.currentThread().getName() + "----- " + value);
}
}
}
}
}
我要的效果不是这样的,如下创建线程的话,
InnerThread innerThread1 = new InnerThread();
InnerThread innerThread2 = new InnerThread();
executor.submit(innerThread1);
executor.submit(innerThread2);
结果:
pool-1-thread-2----- task00
pool-1-thread-1----- task00
pool-1-thread-2----- task11
pool-1-thread-1----- task11
pool-1-thread-2----- task22
pool-1-thread-1----- task22
pool-1-thread-1----- task33
pool-1-thread-2----- task33
pool-1-thread-2----- task44
pool-1-thread-1----- task44
pool-1-thread-2----- task55
pool-1-thread-1----- task55
pool-1-thread-2----- task66
pool-1-thread-1----- task66
pool-1-thread-2----- task77
pool-1-thread-1----- task77
pool-1-thread-2----- task88
pool-1-thread-1----- task88
,我要的不是上面这种效果,我想实现的类似结果如下:
Thread-2------------ task00
Thread-0------------ task22
Thread-4------------ task11
Thread-3------------ task33
Thread-1------------ task44
Thread-1------------ task55
Thread-3------------ task66
Thread-2------------ task77
Thread-0------------ task88