MultiThreadClient.java
上传用户:caijun
上传日期:2022-08-05
资源大小:13k
文件大小:1k
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class MultiThreadClient {
- public static void main(String[] args) {
- int numTasks = 10;
- ExecutorService exec = Executors.newCachedThreadPool();
- for (int i = 0; i < numTasks; i++) {
- exec.execute(createTask(i));
- }
- }
- // Define a simple task for each thread
- private static Runnable createTask(final int taskID) {
- return new Runnable() {
- private Socket socket = null;
- private int port = 8821;
- public void run() {
- System.out.println("Task " + taskID + ":start");
- try {
- socket = new Socket("localhost", port);
- // send close order
- OutputStream socketOut = socket.getOutputStream();
- //socketOut.write("shutdown\r\n".getBytes());
- socketOut.write("bye".getBytes());
- // receive the feedback from server
- BufferedReader br = new BufferedReader(
- new InputStreamReader(socket.getInputStream()));
- String msg = null;
- while ((msg = br.readLine()) != null)
- System.out.println(msg);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- };
- }
- }