控制器,负责与客户端通讯,并且控制着另外12家线程的
12个被控制的线程
package com.amid.entryexit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Controller extends Thread {
private Socket socket;
private StoreOneQuote[] threads;
private BufferedReader in;
private PrintWriter out;
private String regEx;
public Controller(Socket socket, StoreOneQuote[] threads)
throws IOException {
regEx = "END|((STOP|START) [0-9]+)";
this.socket = socket;
this.threads = threads;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//auto-flush
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
}
public void run() {
String request = "";
String response = "";
try {
while (!"END".equals(request)) {
request = in.readLine();
response = request;
if (request.matches(regEx)) {
if ("END".equals(request)) {// end the session between the
// server and the client
response = "OK, end this session, byebye";
} else {// STOP || START
String[] order = new String[2];
order = request.split(" ");
int companyNumber = new Integer(order[1]);
if (companyNumber < threads.length
&& companyNumber >= 0) {
if ("STOP".equals(order[0])) {
response = threads[companyNumber].block();
} else if ("START".equals(order[0])) {
response = threads[companyNumber].wakeUp();
}
} else {
response = "Error: Parameter Out Of Bound";
}
}
} else {
response = "Error: Unknown Request";
}
System.out.println("Client's Request: " + request);
out.println(response);
}// End of while
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
12个被控制的线程
package com.amid.entryexit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
public class StoreOneQuote extends Thread {
private Connection conn = null;
private int sleepTime = 10;
private boolean flag = false;//not wait();
public StoreOneQuote(Connection conn, int sleepTime) {
this.sleepTime = sleepTime;
this.conn = conn;
}
private synchronized void getValuesFromAPI(ArrayList list){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Random r = new Random();
list.add(new Integer(Thread.currentThread().getName()));
list.add(r.nextInt(6));
list.add(r.nextInt(2));
list.add(r.nextInt(100));
list.add(r.nextFloat() + 1);
}
public synchronized String wakeUp(){
if(flag == true){
flag = false;
this.notifyAll();
return "OK: The Thread had run successfully.";
} else {
return "WARNING: The Thread is running now.";
}
}
/**
* @return true means ok
* false means a warn
*/
public String block(){
if(flag == true){
return "WARNING: The Thread had already been locked.";
} else {
flag = true;
return "OK: The Thread had been blocked successfully.";
}
}
private String getDate(){
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(now);
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {//legacy, no use
String sql = "";
sql += "INSERT INTO quote (company_id, product_id, quote_type, quote_amount, quote_price, quote_time) ";
sql += "VALUES (?, ?, ?, ?, ?, ?); ";
ArrayList list = new ArrayList();
getValuesFromAPI(list);
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 1; i < list.size(); i++) {
pstmt.setInt(i, (Integer)list.get(i - 1));
}
pstmt.setFloat(5, (Float)list.get(4));
pstmt.setString(6, getDate());
if(new Random().nextBoolean()){
pstmt.execute();
System.out.println(Thread.currentThread().getName());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
}
package com.amid.entryexit;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class StoreQuote {
Connection conn = null;
String url = "jdbc:mysql://211.94.206.60:3306/entryexit_v15";
String userName = "entryexit";
String password = "entryexit";
int sleepTime = 4000;
int companyAmount = 10;
int serverPort = 7999;
int socketTimeOut = 60000;
private void setProperties() {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(System.getProperty("user.dir")
+ "\\app.properties"));
url = prop.getProperty("url");
userName = prop.getProperty("userName");
password = prop.getProperty("password");
sleepTime = new Integer(prop.getProperty("sleepTime"));
companyAmount = new Integer(prop.getProperty("companyAmount"));
serverPort = new Integer(prop.getProperty("serverPort"));
socketTimeOut = new Integer(prop.getProperty("socketTimeOut"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getReady4DB() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
private StoreOneQuote[] getReady4TH(int threadAmount) {
StoreOneQuote[] threads = new StoreOneQuote[threadAmount];
for (int i = 0; i < threadAmount; i++) {
threads[i] = new StoreOneQuote(conn, sleepTime);
threads[i].setName(Integer.toString(i));
threads[i].start();
}
return threads;
}
public void monitorThread(StoreOneQuote[] threads, int serverPort) {
ServerSocket server = null;
Socket socket = null;
try {
server = new ServerSocket(serverPort);
while (true) {
socket = server.accept();
socket.setSoTimeout(socketTimeOut);
Controller ctrl = new Controller(socket, threads);
ctrl.start();
}
} catch (IOException e) {
try {
if (!server.isClosed())
server.close();
if (!socket.isClosed())
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
}
private void startUp() {
setProperties();
getReady4DB();
StoreOneQuote[] threads = getReady4TH(companyAmount);
monitorThread(threads, serverPort);
}
public static void main(String[] args) {
StoreQuote sq = new StoreQuote();
sq.startUp();
}
private void closeConn() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
[/code]
[code="java"]