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;
}
}

Java 多线程 socket 取款例子 runnable callable的更多相关文章

  1. Java多线程 Socket使用

    点我跳过黑哥的卑鄙广告行为,进入正文. Java多线程系列更新中~ 正式篇: Java多线程(一) 什么是线程 Java多线程(二)关于多线程的CPU密集型和IO密集型这件事 Java多线程(三)如何 ...

  2. java多线程(二)之实现Runnable接口

    一.java多线程方式2: 实现Runnable接口 好处:a. 可以避免由于java单继承带来的局限性. b. 适合多个相同的程序的代码去处理同一个资源的情况, 把线程与程序的代码, 数据有效分离, ...

  3. Java多线程带返回值的Callable接口

    Java多线程带返回值的Callable接口 在面试的时候,有时候是不是会遇到面试会问你,Java中实现多线程的方式有几种?你知道吗?你知道Java中有可以返回值的线程吗?在具体的用法你知道吗?如果两 ...

  4. Java多线程基础知识例子

    一.管理 1.创建线程 Thread public class Main { public static void main(String[] args) { MyThread myThread = ...

  5. Java 多线程Socket编程通讯--实现聊天室代码

    1.创建服务器类 import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import ja ...

  6. 探Java多线程Thread类和Runnable接口之间的联系

    首先复习一下Java多线程实现机制,Java实现多线程方法有如下这么几种: 1.继承了(extends)Thread类 2.实现了(implements)Runnable接口 也就是说  有如下两种情 ...

  7. Java多线程Socket在控制台输出的多人聊天室编程

    服务器端代码 import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java ...

  8. Java 多线程(1)-Thread和Runnable

    一提到Java多线程,首先想到的是Thread继承和Runnable的接口实现 Thread继承 public class MyThread extends Thread { public void ...

  9. java多线程启动的方法runnable和callable

随机推荐

  1. _视图控制对象生命周期-init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear等的区别及用途

    iOS视图控制对象生命周期-init.viewDidLoad.viewWillAppear.viewDidAppear.viewWillDisappear.viewDidDisappear的区别及用途 ...

  2. c++ 回调类成员函数实现

    实现类成员函数的回调,并非静态函数:区分之 #ifndef __CALLBACK_PROXY_H_ #define __CALLBACK_PROXY_H_ template <typename ...

  3. openstack之neutron linuxbridge + vlan组网

    linuxbridge是和linuxbridge plugin匹配的core agent,主要实现L2层的功能和security group的功能.security group的功能逐渐会被neutr ...

  4. sublime text 3解放鼠标的快捷键总结

    Sublime text 3是我最喜欢的代码编辑器,每天和代码打交道,必先利其器,掌握基本的代码编辑器的快捷键,能让你打码更有效率.刚开始可能有些生疏,只要花一两个星期坚持使用并熟悉这些常用的快捷键, ...

  5. visio 2013 破解工具 - KMSpico

    背景:环境是 win7, 64 bit装了 visio 2013 , 可以却不能用它来画图,在网上找了一些破解工具,大都不能解决问题.网上不靠谱的广告型文章太多了,比较头痛. 所幸,终于找到正确的破解 ...

  6. ##DAY9 UITabBarController

    ##DAY9 UITabBarController UIViewController的tabBarController UIViewController的tabBarItem #pragma mark ...

  7. 使用#define定义字面值和伪函数

    #define是C语言提供的宏命令,其主要目的是:在编程时,为程序员提供一定方便,并能在一定程度上提高程序的执行效率.#define将一个标示符定义为一个字符串,该标示符被称为宏,被定义的字符串称为字 ...

  8. MQ学习(一)----JMS规范(转发整合)

    最近进行ActiveMQ的学习,总结下已被不时之需. JMS规范: JMS即Java消息服务(Java Message Service)应用程序接口是一个Java平台中关于面向消息中间件(MOM)的A ...

  9. mysql alter example

    alter table `user_movement_log` AFTER `Regionid` (在哪个字段后面添加) ) default null; //主键 ) unsigned not nul ...

  10. JSP page include taglib

    page include taglib 语法:<%@ 指令名称 属性=值 属性=值 -%> ------------------- page 1.language 默认值java 2.ex ...