1.自定义普通线程执行任务,设置出队列的任务供线程调用
package com.thread;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* @author liuchj
* @version 1.0
* @className MyThreadTask
* @description //TODO
* @date 2019/5/29
**/
public class MyThreadTask {
public static void main(String[] args) {
/**
线程安全的队列
*/
final Queue<String> queue = new ConcurrentLinkedQueue<String>();
//入队列
for (int i = 0; i < 9; i++) {
queue.add("task-" + i);
}
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (queue.size() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = queue.poll();
if (value != "" && null != value)
System.out.println("线程" + Thread.currentThread().getName() + " 执行了task: " + value);
}
}
}).start();
}
}
}
执行结果:
线程Thread-1执行了task: task-0
线程Thread-0执行了task: task-1
线程Thread-4执行了task: task-2
线程Thread-2执行了task: task-3
线程Thread-3执行了task: task-4
线程Thread-1执行了task: task-5
线程Thread-4执行了task: task-7
线程Thread-0执行了task: task-6
线程Thread-2执行了task: task-8
2.创建线程池执行任务,同样以出队列的任务作为线程调用
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 ThreadPoolTask {
/**
* 线程安全的队列
*/
static Queue<String> queue = new ConcurrentLinkedQueue<String>();
static {
//入队列
for (int i = 0; i < 9; i++) {
queue.add("task-" + i );
}
}
public static void main(String[] args) {
//线程池方式
ExecutorService executor = new ThreadPoolExecutor(5, 5,
10L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < queue.size(); i++) {
//提交任务
InnerThread innerThread = new InnerThread();
executor.submit(innerThread);
}
//关闭线程池中所有线程
executor.shutdown();
}
}
/**
* 线程:执行出队列任务的线程
*/
class InnerThread implements Runnable {
@Override
public void run() {
while (ThreadPoolTask.queue.size() > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = ThreadPoolTask.queue.poll();
if (value != "" && null != value) {
System.out.println("线程"+Thread.currentThread().getName() + " 执行了task: " + value);
}
}
}
}
执行结果:
线程pool-1-thread-3 执行了task: task-1
线程pool-1-thread-1 执行了task: task-0
线程pool-1-thread-5 执行了task: task-2
线程pool-1-thread-4 执行了task: task-3
线程pool-1-thread-2 执行了task: task-4
线程pool-1-thread-1 执行了task: task-5
线程pool-1-thread-5 执行了task: task-6
线程pool-1-thread-3 执行了task: task-7
线程pool-1-thread-4 执行了task: task-8
本人初学,仅作为学习资料使用