在amid时写的一个线程同步的东西

控制器,负责与客户端通讯,并且控制着另外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"]
Sure, I'd be happy to help you with that. Here's a 500-word English essay about a typical day with a PE teacher: A day in the life of a PE teacher is filled with activity, enthusiasm and energy. It starts early in the morning with a refreshing workout session or a jog to keep fit and stay focused for the day. Once the workout is done, it is time to gear up for the tasks ahead. As the school bell rings, students start arriving to the PE field. The first task of the teacher is to welcome them all and put them into action. Depending on the day, the teacher may have several classes to teach back to back or maybe a few hours in between to prepare for the next class. Nevertheless, the teacher must stay on top of the schedule to ensure no time is wasted. During class, the teacher shows mastery and expertise in the different exercises and techniques to keep students active and engaged. The teacher carefully instructs the students about the proper way to stretch, practice their drills, and to work on their stamina. The teacher also is available for questions and feedback, ensuring that every student has the support they need to learn and grow. Amid the exercises, the teacher is always watching for the students' safety, ready to provide encouragement where needed, and always mindful of the particular needs of each individual student. The teacher ensures that the students work at their own pace and that each student is challenged enough to push their limits without becoming discouraged. The PE teacher also serves as a mentor, guiding students on a path towards a healthier life with good habits, discipline, and self-awareness. This guidance goes beyond the simple exercises and includes helping individuals find their strengths, passions, and talents unique to them. Once the class has come to an end, the teacher must do his or her part to put away all equipment and make sure that the field is safe and clean for
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值