マルチスレッド共通接続挿入データ

2347 ワード

問題のように、マルチスレッドが1つの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!
" ,e); } } } } }

 


 

実行結果:


1000個のデータを挿入します.したがって、sql文の実行には原子性があるはずです.