多线程实例

需要执行该实例,请用下面的命令行

java TestMT [THREADS_NUMBER] [-s]

其中THREADS_NUMBER是本实例中线程个数,如果不写默认为5

-s是指线程间是否共享连接,如果不写,默认线程间不共享连接

package com.sun.cts.tests.jdbc.help_doc.shi_li;

import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileInputStream;
/**************************************************
 *这个例子演示多线程
 **************************************************/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.junit.Test;

public class MTTest {

	/* 缺省为5个线程 */
	private static int THREADS_NUM = 5;
	/* 使所有线程一起运行的标志 */
	private static boolean greenLight = false;
	/* 共享的连接 */
	private static Connection con;
	/* 下一个线程编号 */
	public static int nextId = 1;
	public static String DBUSER = "";
	public static String DBPASSWD = "";
	public static String DBURL = "";
	public static String DBDRIVER = "";

	public static void init() {
		Properties prop = new Properties();
		try {

			FileInputStream in = new FileInputStream(
					"." + File.separator + "testFile" + File.separator + "cts_env.properties");
			prop.load(in);
			in.close();
		} catch (Exception e) {
			fail(e.getMessage());
			e.printStackTrace();
		}
		// 从配置文件中读取
		// DBUSER = "sysdba";
		DBUSER = prop.getProperty("DBUSER");
		// DBPASSWD = "szoscar55";
		DBPASSWD = prop.getProperty("DBPASSWD");
		// DBURL = "jdbc:oscar://localhost:2003/osrdb";
		DBURL = prop.getProperty("DBURL");
		// DBDRIVER = "com.oscar.Driver";
		DBDRIVER = prop.getProperty("DBDRIVER");
		try {
			Class.forName(DBDRIVER);
			con = DriverManager.getConnection(DBURL, DBUSER, DBPASSWD);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static synchronized void setGreenLight() {
		greenLight = true;
	}

	synchronized boolean getGreenLight() {
		return greenLight;
	}

	class ExcuteThread extends Thread {
		/* 每个线程的id */
		private int threadId;
		private Connection con;

		public ExcuteThread(int id) {
			super();
			// 设置当前线程的id
			threadId = id;
			con = null;
		}

		public ExcuteThread(int id, Connection con) {
			super();
			// 设置当前线程的id
			threadId = id;
			this.con = con;
		}

		public void run() {
			Connection conn = null;
			ResultSet rs = null;
			Statement stmt = null;
			try {
				// 创建Statment对象
				if (con != null)
					// 共享连接
					stmt = con.createStatement();
				else {
					Class.forName(DBDRIVER);
					conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWD);
					stmt = conn.createStatement();
				}
				// 等待,直到可以开始运行
				while (!getGreenLight()) {
					yield();
				}
				// 获得结果集
				rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");
				// 取得记录,并打印记录
				while (rs.next()) {
					System.out.println(
							"Thread " + threadId + " Employee Id : " + rs.getInt(1) + " Name : " + rs.getString(2));
					// 操作停止,让其他线程运行
					yield();
				}
				// 关闭资源
				rs.close();
				rs = null;
				stmt.close();
				stmt = null;
				// 如果不是共享连接,关闭本线程的连接
				if ((con == null) && (conn != null)) {
					conn.close();
					conn = null;
				}
				// 线程结束
				System.out.println("Thread " + threadId + " is finished. ");
			} catch (Exception e) {
				System.out.println("Thread " + threadId + " got Exception: " + e);
				fail(e.getMessage());
			}
		}

	}

	public void executePrivateCon() throws Exception {
		Thread[] threadList = new Thread[THREADS_NUM];
		// 启动线程
		for (int i = 0; i < THREADS_NUM; i++) {
			threadList[i] = new ExcuteThread(nextId);
			nextId++;
			threadList[i].start();
		}
		// 同一时间使所有线程运行起来
		setGreenLight();
		// 主线程等待所有线程结束
		for (int i = 0; i < THREADS_NUM; i++) {
			threadList[i].join();
		}
	}

	public void executeShareCon() throws Exception {
		Thread[] threadList = new Thread[THREADS_NUM];
		// 启动线程
		for (int i = 0; i < THREADS_NUM; i++) {
			threadList[i] = new ExcuteThread(nextId, con);
			nextId++;
			threadList[i].start();
		}
		// 同一时间使所有线程运行起来
		setGreenLight();
		// 主线程等待所有线程结束
		for (int i = 0; i < THREADS_NUM; i++) {
			threadList[i].join();
		}
	}

	@Test
	public void execute() {
		MTTest.init();
		// 创建表
		String creSql = "CREATE TABLE EMPLOYEE" 
					  + "(id INT not NULL,name varchar(255),PRIMARY KEY ( id ))";
		String insSql = "INSERT INTO EMPLOYEE VALUES(1,'shentong')";
		String dropSql = "DROP TABLE EMPLOYEE ";

		Statement stmt;
		try {
			stmt = con.createStatement();
			// 创建表
			stmt.executeUpdate(creSql);
			// 插入数据
			stmt.executeUpdate(insSql);
			
			//线程私有连接
			executePrivateCon();
			//线程共享连接
			executeShareCon();

			// 删除表
			stmt.executeUpdate(dropSql);
			stmt.close();
			con.close();
		} catch (SQLException e) {
			fail(e.getMessage());
		} catch (Exception e) {
			fail(e.getMessage());
		}

	}

	public static void main(String args[]) {
		new MTTest().execute();
	}

}