Java自定义多线程服务器
// multi.MultiServer.java
package multi;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiServer {
private int port = 8000;
private int backlog = 42;
private ServerSocket server_socket;
private ThreadPool threadPool;
private final int POOL_SIZE = 7;
public MultiServer()throws IOException{
server_socket = new ServerSocket();
server_socket.setReuseAddress(true);
server_socket.bind(new InetSocketAddress(port),backlog);
int system_cpu_total = Runtime.getRuntime().availableProcessors();
threadPool = new ThreadPool(POOL_SIZE * system_cpu_total);
System.out.println("--- server started! ---");
}
public void service(){
while(true){
try{
Socket socket = server_socket.accept();
threadPool.execute(new WorkHandler(socket));
} catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args)throws Exception {
MultiServer server = new MultiServer();
server.service();
}
}
// multi.ThreadPool.java
package multi;
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup{
private static int threadPoolId;
private boolean isClosed = false;
private LinkedList<Runnable> workQueue;
public ThreadPool(int poolSize){
super("ThreadPool-" + (threadPoolId++));
setDaemon(true);
workQueue = new LinkedList<Runnable>();
for(int i=0;i<poolSize;i++){
new WorkThread(this,i).start(); // 启动工作者线程
}
}
public synchronized void execute(Runnable task){
if(isClosed){
throw new IllegalStateException("The " + getName()
+ " has closed!");
}
if(task != null){
workQueue.add(task);
// 一次只有一个线程取任务[getTask() 被 synchronized 修饰]
// 所有此处没有使用notifyAll();
相关文档:
第一种方法为常见且易于上手
1、在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作
等。对于这样的操作最方便、高效的实现方式就是使用java.util.Timer工具类。
private java.util.Timer timer;
timer
= new Timer(true);
timer.schedule(
new java.util.TimerTask() {
public void run() { // ......
注意,用到了内部类:
new Thread
(
new Runnable()
{
public void run()
{
try
&n ......
首先请大家看看下面两段代码有什么区别:
代码1:
List<Task> tasks = new ArrayList<Task>();
Task[] allTask = DemoData.getTasksData();
for(int i=0;i<allTask.length;i++){
tasks.add(allTask[i]);
}
------------------------------------- ......
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ZipUtil {
public static void main(String[] args) {
&nb ......
1.整数
byte 1字节
short 2字节
int 4字节
long 8字节
2.浮点
float
double
提示
(1) 浮点型的值,如果没有特别指明,默认是 double 型的
(2) 定义 float 型的时候,一定要指明是 float 型的,可以通过在数字后面添加&rd ......