多线程共用一个Connection插入数据

如题,测试多线程共用一个Connection是否会影响sql语句的执行结果

package com.zw.mgt;

import org.junit.Test;
import org.voovan.dbutil.DbOperate;
import org.voovan.tools.TSQL;
import org.voovan.tools.log.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ThreadTest {
    @Test
    public void test() throws InterruptedException, SQLException {
        DbOperate dbOperate = new DbOperate();
        Connection connection = dbOperate.getConnection();
        ThreadDemo threadDemo1 = new ThreadDemo(connection);
        ThreadDemo threadDemo2 = new ThreadDemo(connection);
        ThreadDemo threadDemo3 = new ThreadDemo(connection);
        ThreadDemo threadDemo4 = new ThreadDemo(connection);
        ThreadDemo threadDemo5 = new ThreadDemo(connection);
        ThreadDemo threadDemo6 = new ThreadDemo(connection);
        ThreadDemo threadDemo7 = new ThreadDemo(connection);
        ThreadDemo threadDemo8 = new ThreadDemo(connection);
        ThreadDemo threadDemo9 = new ThreadDemo(connection);
        ThreadDemo threadDemo10 = new ThreadDemo(connection);
        threadDemo1.start();
        threadDemo2.start();
        threadDemo3.start();
        threadDemo4.start();
        threadDemo5.start();
        threadDemo6.start();
        threadDemo7.start();
        threadDemo8.start();
        threadDemo9.start();
        threadDemo10.start();
        Thread.sleep(1000*60*5);
    }

    public class ThreadDemo extends Thread{
        public ThreadDemo(Connection connection){
            this.connection = connection;
        }
        private Connection connection;
        public void run(){
            for (int i = 0; i < 100; i++) {
                PreparedStatement preparedStatement = null;
                try {
                    preparedStatement = TSQL.createPreparedStatement(connection, "insert into test values(\""+Thread.currentThread().getName()+":"+i+"\")", null);
                    preparedStatement.executeUpdate();
                } catch (SQLException e) {
                    Logger.error("Update excution SQL Error!\n" ,e);
                }
            }
        }
    }
}


 

 

执行结果:

插入1000条数据。所以sql语句执行应该具有原子性。

你可能感兴趣的:(多线程共用一个Connection插入数据)