Java 多线程 socket 取款例子 runnable callable

socket部分参考 http://blog.csdn.net/kongxx/article/details/7259465

取款部分参考 http://blog.csdn.net/dayday1987/article/details/9971647

先说说取款吧  如何保证数据同步? 操作时加锁即可  怎么加?使用synchronized关键字

然后自己设置两个线程  一个add  一个withdraw即可(原博中只用到了Runnable  感觉并没有创建新线程 这里有点小疑问)

socket部分  每次server.accpet()之后都会返回一个客户端  Server端需要创建一个新的线程 将客户端放入该新thread中处理就行

所以这里模拟的一个客户端专门存  一个专门取

Server端

package com.googlecode.garbagecan.test.socket.sample2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.accout.Operation;
/**
 * http://blog.csdn.net/kongxx/article/details/7259465
 * @author Administrator
 *
 */
public class MyServer {
    static Operation oper;
    public static void main(String[] args) throws IOException {
        oper = new Operation();
        MyServer ms=new MyServer();
        
        ServerSocket server = new ServerSocket(12345);
        
        while (true) {
            Socket socket = server.accept();
            System.out.println("a new conntection ---------------");
            ms.invoke(socket);
        }
    }
    
    private static void invoke(final Socket client) throws IOException {
        new Thread(new Runnable() {
            public void run() {
                BufferedReader in = null;
                PrintWriter out = null;
                try {
                    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    out = new PrintWriter(client.getOutputStream());

                    
                    while (true) {
                        String msg = in.readLine();
                        if (msg==null||msg.equals("bye")) {
                            break;
                        }
                        System.out.println("client says "+msg);
                        String val[]=getParam(msg);
                        //msg1 add
                        if(val[0].equals("1")){
                            msg=oper.addOperationCall(val[1],Integer.parseInt(val[2]));
                        }else if(val[0].equals("2")){
                            msg=oper.withDrawOperationCall(val[1],Integer.parseInt(val[2]));
                        }
                        //send msg to client
                        out.println(msg);
                        out.flush();
                    }
                } catch(IOException ex) {
                    ex.printStackTrace();
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                    } catch (Exception e) {}
                    try {
                        out.close();
                    } catch (Exception e) {}
                    try {
                        client.close();
                    } catch (Exception e) {}
                }
            }
        }).start();
    }
    
    static String[] getParam(String msg){
        String val[]=msg.split(" ");
        return val;
    }
}

取客户端

package com.googlecode.garbagecan.test.socket.sample2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClientLoopDraw {
        public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 12345);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedReader readConsole = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        int index=0;
        while (true) {
            //暂时规定1 就是add  2就是取钱  
//            String msg = readConsole.readLine();
            //读取控制台的信息(并加上名字)并发给Server
            //some codes to handle msg
            String msg="2 jerry 150 -";
            System.out.println(msg);
            out.println(msg);
            out.flush();
            System.out.println("Server says "+in.readLine());
            if (msg.equals("bye")||index++>=10) {
                break;
            }
            
        }
        socket.close();
    }
}

存客户端

package com.googlecode.garbagecan.test.socket.sample2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClientLoopAdd {
        public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 12345);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedReader readConsole = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        int index=0;
        while (true) {
            //暂时规定1 就是add  2就是取钱  
            //String msg = readConsole.readLine();
            //读取控制台的信息(并加上名字)并发给Server
            //some codes to handle msg
            String msg="1 tom 100 +";
            System.out.println(msg);
            out.println(msg);
            out.flush();
            System.out.println("Server says "+in.readLine());
            if (msg.equals("bye")||index++>10) {
                break;
            }
            
        }
        socket.close();
    }
}

创建操作类  方法中创建新的线程来处理存钱和取钱

package com.accout;

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

public class Operation {

    Account account = new Account();

    public void addOperation(final String name, final float varient) {

        // 加载线程
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 存钱
                getAccount().add(name, varient);
            }

        }).start();
//        new Runnable() {
//
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                // 存钱
//                getAccount().add(name, varient);
//            }
//
//        }.run(); // 别忘了加run()
    }

    public void withdrawOperation(final String name, final float varient) {

        // 加载线程
        new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 取钱
                getAccount().withdraw(name, varient);
            }

        }.run();
    }

    public String addOperationCall(final String name, final float varient)
            throws Exception {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                return getAccount().add(name, varient);
            }
        });
        String rs = null;
        try {
            Thread.sleep(1000);// 可能做一些事情
            rs = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;

    }

    public String withDrawOperationCall(final String name, final float varient)
            throws Exception {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                return getAccount().withdraw(name, varient);
            }
        });
        String rs = null;
        try {
            Thread.sleep(1000);// 可能做一些事情
            rs = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;

    }    
    
    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }
}
原文地址:https://www.cnblogs.com/cart55free99/p/3634871.html