日期:2014-05-20 浏览次数:20959 次
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDao {
public static void main(String[] args) throws Exception {
Dao dao=new Dao();
dao.conn();
ExecutorService pool = Executors.newFixedThreadPool(2);
for(int i=0;i<100;i++){//模拟网络发来的100个包
pool.execute(new Runnable() {
@Override
public void run() {
System.out.print("c");
}
});//模拟接受包 是不是应该放到循环100次外面?
pool.execute(new Parse(dao));//取出解析包 是不是应该放到循100次外面?
}
}
}
class Parse implements Runnable{
public Dao dao;
public Parse(Dao dao) {
this.dao = dao;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(500);
dao.save();//可能有2个线程同时访问同一个dao对象
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Dao{
static int cnt=0;
PreparedStatement ps;Connection c;
public void conn() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","","");
c.setAutoCommit(false);
ps = c.prepareStatement("insert into u values(?)");
}
public void save() throws Exception{
ps.setInt(1, 33);
ps.addBatch();//可能有2个线程同时访问同一个ps对象 结果容易出错
cnt++;
if(cnt%50==0){
ps.executeBatch();
c.commit();
ps.clearBatch();
}
// Thread.sleep(500);
}
}