16k闪存大脑3954634
2017-09-19 16:34

军队作战到什么时候才会进行下一步Thread.sleep(50)呢
同问?
了解了线程,可以去了解下 队列, 对于处理高并发,和提高业务数据吞吐量会很有用。
package com.junbao.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadTest {
static ExecutorService executorService = Executors . newFixedThreadPool (5) ;
@SuppressWarnings("deprecation")
public static void main(String[] args) throws InterruptedException {
ThreadTest test = new ThreadTest();
List<Integer> numList = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
numList.add(i);
}
// 队列
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(numList.size());
// 放入
try {
for (Integer ints : numList) {
queue.put(ints);
}
} catch (Exception e) {
// TODO: handle exception
}
final List<Integer> outList = new ArrayList<Integer>();
for (int j = 0; j < 5; j++) {
new Thread() {
public void run() {
while (true) {
try {
// 将此处的睡眠时间分别改为100和1000,观察运行结果
Thread.sleep((int) (Math.random() * (1000 - 100) + 100));
String name1 = Thread.currentThread().getName();
System.out.println(name1 + "准备取数据!");
Integer num = queue.take();// 如果没有了数据,就会阻塞
String name2 = Thread.currentThread().getName();
outList.add(num);
System.out.println(name2 + "已经取走数据," + "队列目前有" + queue.size() + "个数据");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NoSuchElementException e1) {
// TODO: handle exception
}
}
}
}.start();
}
try {
while (true) {
if (queue.isEmpty()) {
System.out.println("空了,可以执行其他的任务了:打印输出转以后的列表");
test.showList(outList);
System.out.println(Thread.currentThread().getState());
break;
}
}
} catch (Exception e) {
// TODO: handle exception
}
test();
}
public void showList(List<Integer> list) {
System.out.println(list.toString());
}
public static void test(){
System.out.println("继续往下执行,看看还有什么可以做");
}
}
谁说一定要结束才会执行sleep,不是说你能很准确知道作战到什么时候会进行下一步,两个线程运行是状态是交互的,然后你还有个stage线程,三个线程都是独立的。你这两个运行会,他还是会运行stage线程里的sleep方法的。
我觉得应该是上面两个线程都结束了,才继续进行下面的sleep,你可以将50设置的大一点,比如好几毫秒,然后你可以看一下运行结果。
深入浅出Java多线程
186066 学习 · 502 问题
相似问题