n 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Java中使用Executors创建和管理线程(3)
时间:2011-03-24 zhangjunhd
4.4 使用SingleThreadExecutor启动线程
SingleThreadExecutor.java
package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++)
exec.execute(new MyThread(i));
exec.shutdown();
}
}
结果:
Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Create Thread-4
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
5.配合ThreadFactory接口的使用
我们试图给线程加入daemon和priority的属性设置。
5.1设置后台线程属性
DaemonThreadFactory.java
package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;
public class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}
5.2 设置优先级属性
最高优先级MaxPriorityThreadFactory.java
package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;
public class MaxPriorityThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
}
}
最低优先级MinPriorityThreadFactory.java
package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;
public class MinPriorityThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
}
Java中使用Executors创建和管理线程(4)
时间:2011-03-24 zhangjunhd
5.3启动带有属性设置的线程
ExecFromFactory.java
package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zj.concurrency.executors.factory.DaemonThreadFactory;< BR> import com.zj.concurrency.executors.factory.MaxPriorityThreadFact ory;
import com.zj.concurrency.executors.factory.MinPriorityThreadFact ory;
public class ExecFromFactory {
public static void main(String[] args) throws Exception {
ExecutorService defaultExec = Executors.newCachedThreadPool();
ExecutorService daemonExec = Executors
.newCachedThreadPool(new DaemonThreadFactory());
ExecutorService maxPriorityExec = Executors
.newCachedThreadPool(new MaxPriorityThreadFactory());
|