多线程的一些其他操作:
sleep
public class SleepingTask implements Runnable {
private int countDown = 100;
private static int taskCount = 0;
private final int id = taskCount++;
public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "lift off") + ")";
}
@Override
public void run() {
// TODO Auto-generated method stub
while (countDown-- > 0) {
System.out.println(status());
try {
// old style
// Thread.sleep(100);
//JavaSE 5/6 style
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("interrupted!");
}
}
}
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
SleepingTask sleepingTask = new SleepingTask();
for (int i = 0; i < 10; i++) {
//线程不安全的
service.execute(sleepingTask);
}
}
}
线程阻塞 使得任务调度器可以切换到另一个线程,进而可以驱动另一个任务。但是也的看底层系统实现
优先级
调度器倾向于让优先级更高的线程先执行,绝大数情况下线程以默认的优先级执行。
public class SimplePriority implements Runnable {
private int priority;
private int countDown=5;
public SimplePriority(int priority) {
super();
this.priority = priority;
}
@Override
public String toString() {
return Thread.currentThread().getName() + " priority:" + priority + " countDown:" + countDown;
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
while (true) {
for (int i = 0; i < 1000; i++) {
@SuppressWarnings("unused")
double a = (Math.PI + Math.E) / i;// 耗时操作
if (i % 100 == 0) {
Thread.yield();
}
}
System.out.println(this);
if (--countDown == 0)
return;
}
}
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
for(int i=0;i<5;i++){
service.execute(new SimplePriority(Thread.MIN_PRIORITY));
}
service.execute(new SimplePriority(Thread.MAX_PRIORITY));
service.shutdown();
}
}
结果:
pool-1-thread-1 priority:1 countDown:5
pool-1-thread-6 priority:10 countDown:5
pool-1-thread-4 priority:1 countDown:5
pool-1-thread-5 priority:1 countDown:5
pool-1-thread-3 priority:1 countDown:5
pool-1-thread-2 priority:1 countDown:5
pool-1-thread-5 priority:1 countDown:4
pool-1-thread-4 priority:1 countDown:4
pool-1-thread-6 priority:10 countDown:4
pool-1-thread-1 priority:1 countDown:4
pool-1-thread-6 priority:10 countDown:3
pool-1-thread-1 priority:1 countDown:3
pool-1-thread-6 priority:10 countDown:2
pool-1-thread-4 priority:1 countDown:3
pool-1-thread-5 priority:1 countDown:3
pool-1-thread-6 priority:10 countDown:1
pool-1-thread-2 priority:1 countDown:4
pool-1-thread-3 priority:1 countDown:4
pool-1-thread-2 priority:1 countDown:3
pool-1-thread-5 priority:1 countDown:2
pool-1-thread-4 priority:1 countDown:2
pool-1-thread-1 priority:1 countDown:2
pool-1-thread-5 priority:1 countDown:1
pool-1-thread-1 priority:1 countDown:1
pool-1-thread-2 priority:1 countDown:2
pool-1-thread-3 priority:1 countDown:3
pool-1-thread-2 priority:1 countDown:1
pool-1-thread-3 priority:1 countDown:2
pool-1-thread-3 priority:1 countDown:1
pool-1-thread-4 priority:1 countDown:1
可以看出优先级高的话执行的频率更高