`
wuzijingaip
  • 浏览: 318671 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

java 线程池

    博客分类:
  • java
阅读更多
package com.fx.test;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class TaskExecutionWebServer {
	private static final int NTHREADS = 100;
	// 使用线程池来避免 为每个请求创建一个线程。
	private static final Executor threadPool = Executors.newFixedThreadPool(NTHREADS);
	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8011);
		while (true) {
			final Socket socket = server.accept();
			threadPool.execute(new Runnable() {
				public void run() {
					handleRequest(socket);
				}
			});
		}
	}
	protected static void handleRequest(Socket socket) {
		System.out.println(Thread.currentThread().getId());
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


package com.fx.test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class LifeCycleWebServer {
	private static final int NTHREADS = 100;
	private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

	public void start() throws IOException {
		ServerSocket server = new ServerSocket(8011);
		while (exec.isShutdown()) {
			try {
				final Socket socket = server.accept();
				exec.execute(new Runnable() {
					public void run() {
						handleRequest(socket);
					}
				});
			} catch (RejectedExecutionException e) {
				if (!exec.isShutdown()) {
					// log.error(...)
				}
			}
		}
	}

	protected void handleRequest(Socket socket) {
		Request req = readRequest(socket);
		if (isShutDown(req)) {
			stop();
		} else {
			dispatchRequest(req);
		}
	}

	public void stop() {
		exec.shutdown();
	}

	// ~ Mock Object And Function..
	private static class Request {

	}

	private Request readRequest(Socket socket) {
		// TODO Auto-generated method stub
		return null;
	}

	private boolean isShutDown(Request req) {
		// TODO Auto-generated method stub
		return false;
	}

	private void dispatchRequest(Request req) {
		// TODO Auto-generated method stub
	}

}


package com.fx.test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class LifeCycleWebServer {

	private static final int NTHREADS = 100;

	private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

	public void start() throws IOException {
		ServerSocket server = new ServerSocket(8011);
		while (exec.isShutdown()) {
			try {
				final Socket socket = server.accept();
				exec.execute(new Runnable() {
					public void run() {
						handleRequest(socket);
					}
				});

			} catch (RejectedExecutionException e) {
				if (!exec.isShutdown()) {
					// log.error(...)
				}
			}
		}
	}

	protected void handleRequest(Socket socket) {
		Request req = readRequest(socket);
		if (isShutDown(req)) {
			stop();
		} else {
			dispatchRequest(req);
		}
	}

	public void stop() {
		exec.shutdown();
	}

	// ~ Mock Object And Function..
	private static class Request {

	}
	private Request readRequest(Socket socket) {
		// TODO Auto-generated method stub
		return null;
	}

	private boolean isShutDown(Request req) {
		// TODO Auto-generated method stub
		return false;

	}

	private void dispatchRequest(Request req) {
		// TODO Auto-generated method stub
	}

}


package com.fx.test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class LifeCycleWebServer {

	private static final int NTHREADS = 100;

	private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

	public void start() throws IOException {
		ServerSocket server = new ServerSocket(8011);
		while (exec.isShutdown()) {

			try {
				final Socket socket = server.accept();
				exec.execute(new Runnable() {
					public void run() {
						handleRequest(socket);
					}
				});
			} catch (RejectedExecutionException e) {
				if (!exec.isShutdown()) {
					// log.error(...)
				}
			}
		}
	}

	protected void handleRequest(Socket socket) {
		Request req = readRequest(socket);
		if (isShutDown(req)) {
			stop();
		} else {
			dispatchRequest(req);

		}
	}

	public void stop() {
		exec.shutdown();
	}

	// ~ Mock Object And Function..
	private static class Request {

	}

	private Request readRequest(Socket socket) {
		// TODO Auto-generated method stub
		return null;
	}

	private boolean isShutDown(Request req) {
		// TODO Auto-generated method stub
		return false;
	}

	private void dispatchRequest(Request req) {
		// TODO Auto-generated method stub
	}

}


package com.fx.test;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.sun.scenario.effect.ImageData;

public class FutureRenderer2 {

	private static final int NTHREADS = 100;

	private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

	void renderPage(CharSequence source) {
		final List<ImageInfo> imageinfos = scanForImageInfo(source);
		CompletionService<ImageData> completionService = new ExecutorCompletionService<ImageData>(exec);
		for (final ImageInfo imageinfo : imageinfos) {
			completionService.submit(new Callable<ImageData>() {
				public ImageData call() throws Exception {
					// 提高性能点一: 将顺序的下载,变成并发的下载,缩短下载时间
					return imageinfo.downloadImage();
				}
			});
		}
		renderText(source);
		try {
			for (int i = 0; i < imageinfos.size(); i++) {
				Future<ImageData> f = completionService.take();
				// 提高性能点二: 下载完成一张图片后,立刻渲染到页面。
				ImageData imagedata = f.get();
				reanderImage(imagedata);
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	private void renderText(CharSequence source) {
		// TODO Auto-generated method stub
	}

	private void reanderImage(ImageData data) {
		// TODO Auto-generated method stub
	}

	private List<ImageInfo> scanForImageInfo(CharSequence source) {
		// TODO Auto-generated method stub
		return null;
	}

}

package com.lvyou.fx.test.threadPool;

import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/** 
 * task2
 * @author arron
 * @date 2015年8月5日 下午2:08:34 
 * @version 1.0 
 */
public class ScheduleTask {

	public static void main(String[] args) {
		ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);//启用2个线程
		Task1 t1 = new Task1();
		// 马上运行,任务消耗3秒。运行结束后等待2秒。【有空余线程时】,再次运行该任务
		pool.scheduleWithFixedDelay(t1, 0, 2, TimeUnit.SECONDS);
		
		// 马上运行,任务消耗5秒,运行结束后等待2秒。【有空余线程时】,再次运行该任务
		Task2 t2 = new Task2();
		pool.scheduleWithFixedDelay(t2, 0, 2, TimeUnit.SECONDS);
		
	}
	
	public static class Task1 extends TimerTask{

		@Override
		public void run() {
			System.out.println("----task1 start--------"+new Date().toLocaleString());
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("----5s later, task1 end--------"+new Date().toLocaleString());
		}
		
	}
	public static class Task2 extends TimerTask{

		@Override
		public void run() {
			System.out.println("----task2 start--------"+new Date().toLocaleString());
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("----5s later, task2 end--------"+new Date().toLocaleString());
		}
		
	}
}

package com.lvyou.fx.test.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * Executors是线程池框架的一个工具类
 * 
 */
public class FixedThreadPoolDemo {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(2);

		// 定义一个循环,添加5个任务
		for (int i = 0; i < 5; i++) {
			int flag = i;
			pool.execute(new Runnable() {
				// 任务详情:执行6次打印语句。
				@Override
				public void run() {
					for (int j = 0; j < 6; j++) {
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName() + " " + flag + " " + " `s loop : " + j);
					}
				}
			});
		}

		pool.shutdown();

	}
}

package com.lvyou.fx.test.threadPool;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FutureDemo {
	public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
		// CompletionService接口内部维护一个结果队列:一堆future....
		CompletionService<Integer> cs = new ExecutorCompletionService<>(pool);
		for (int i = 1; i < 11; i++) {
			final int flag = i * 10;
			cs.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					Thread.sleep(1000);
					return flag;
				}
			});
		}

		for (int i = 0; i < 11; i++) {
			try {
				System.out.println(cs.take().get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		pool.shutdown();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics