/** 
D:/record.txt 文件是一行一行的文字,每行文字其实是一个十位数,文件中基本没重复的数字 
我就是将其插入mysql 的record表中,record表只有一列id,定义为varchar(13) unique key 
结果我几十个线程,每秒钟也插入一百左右,并且cpu空闲的很 
请问是怎么回事啊,代码如下 
*/ 
import com.mysql.jdbc.*; 
public class Try implements Runnable{ 
private static BufferedReader in ; public static void main( String[] args ) { 
for( int i=0;i <57;i++ ) { 
new Thread(new Try()).start(); 

} public Try() { 
if( in != null ) return ; 
try{ 
in = new BufferedReader( new FileReader("D:/record.txt") ); 
}catch( Exception e ){ 
e.printStackTrace(); 

} public void run() { 
java.sql.Connection con; 
java.sql.Statement sta; 
try{ 
Class.forName("com.mysql.jdbc.Driver" ); 
String url = "jdbc:mysql://localhost:3306/test"; 
con = java.sql.DriverManager.getConnection(url,"root","password");    
    String line; 
    int N=0; 
    while( (line=in.readLine())!=null ) { 
    try{ 
    con.createStatement().execute("insert into record values('"+line.trim()+"')" ); 
    N++; 
    }catch( Exception e ){ 
    System.out.println( "N"+N +e.toString() ); 
    } 
    } 
    System.out.println( N ); 
}catch( Exception e ){ 
e.printStackTrace(); 

} } 

解决方案 »

  1.   

    IO操作都慢,不是mysql的问题。
      

  2.   

    你创建的STATIC的BufferedReader对象有必要吗?
    你创建的57个线程,建立了57个连接,每个线程都在读文件,并插入数据库,但是这些线程却不是,但是I/O资源是有限的,就算你这样,
    还是不能并发的,因为当一个线程在占用I/O资源的时候,其他大多线程都在等待I/O资源,不能提高速度的。
    另外,建立为STATIC的其实并不好,因为STATIC是JVM的,由JVM来管理的,不能被自动释放的,也是占用大量资源的。