多线程笔记

来源:互联网 发布:文件制作软件 编辑:程序博客网 时间:2024/06/06 02:06
package demo;


import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


public class BooundedExecutor {


private  Executor exec;
private  Semaphore semaphore;
public BooundedExecutor(Executor exec, int bound){
this.exec = exec;
this.semaphore = new Semaphore(bound);
}

public void submit(final Runnable command) throws InterruptedException{


exec.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
command.run();
System.out.println("线程"+Thread.currentThread().getId()+"线进入,当前并发数"+ (20 - semaphore.availablePermits()));
Thread.sleep(500);
} catch (InterruptedException e) {
} finally {
semaphore.release();
}
System.out.println("第条"+Thread.currentThread().getId()+"线程离开,当前并发数"+ (20 - semaphore.availablePermits()));
}
});
}
public static void main(String[] args) throws InterruptedException {
int size =  20;
int bound =  20;
ExecutorService exec = Executors.newFixedThreadPool(size);
BooundedExecutor booundExecutor = new BooundedExecutor(exec, bound);
for (int i = 0; i < 20; i++){
TaskRunnable command = new TaskRunnable("www.baidu.com", null);
booundExecutor.submit(command);
}
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
System.out.println("所有任务结束");
}

private static class TaskRunnable implements Runnable{


private String url = null;
private String parm = null;

public TaskRunnable(String url, String parm){
this.url = url;
this.parm = parm;
}
@Override
public void run() {
try {
/* String response = HttpUtil.openStream(url, parm);
System.out.println(response);*/
} catch (Exception e) {

}finally{
HttpUtil.close();
}
}

}
}























0 0
原创粉丝点击