我们如何在java中并行运行两个线程

时间:2014-02-01 10:04:34

标签: java multithreading

我想并行运行两个线程。我的要求是: - 在数据库中有两个表 - table1和table2。在表1中有1000条记录。一个线程将从table1读取100行,并将这些行数据传递给线程2。线程二会将这些行插入table2。当线程1从table1获取数据时,线程2应处于等待状态,当线程2将数据插入表2时,线程One shuld处于等待状态。我们如何做到这一点。

嗨,我已经写了这段代码。请分享您的看法我们如何改进此代码也使用等待和通知方法的线程..

类ProcessDataUsingThread扩展了线程{

private Connection con = null;
private Statement st = null;
//  private String query = null;
private ResultSet rs = null;
private int i = 0;
private int totalRows = 0;
static ProcessDataUsingThread t1;
static ProcessToInsertData t2;
// ArrayList al;

public static void main(String... arg) {
    t1 = new ProcessDataUsingThread();
    t1.setName("Thread-1");
    t1.start();
    // t2.start();
    //   t2.suspend();
}

@Override
public void run() {
    fetchRecord();
}

public void fetchRecord() {

    try {
        con = new DatabaseConnection().getConnection();
        st = con.createStatement();
        // Find Total no. of rows in tha table
        ResultSet resultSet = st.executeQuery("select count(*) As Rows from customer;");
        while (resultSet.next()) {
            totalRows = resultSet.getInt("Rows");
        }
        System.out.println("Total no. of rows are : " + totalRows);

        while (i <= totalRows) {
            System.out.println(getName() + " is getting execute. . . .");
            rs = st.executeQuery("Select * from Customer LIMIT " + i + ", 10");
            i += 10;

            //  t1.suspend();
            new ProcessToInsertData(rs, t1).start();
            t1.suspend();
            // t2.notify(); 
            //  t2.start(); 
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //  return al; 
}

}

/ **  *线程的第二课  *  * @author abc  * / class ProcessToInsertData扩展Thread {

private Connection con = null;
private final int BATCH_EXECUTION_LIMIT = 20;
private int counter = 0;
private PreparedStatement preparedStatement = null;
private ResultSet rs = null;
private ProcessDataUsingThread pd = null;

public ProcessToInsertData(ResultSet resultSet, ProcessDataUsingThread pd) {
    this.rs = resultSet;
    this.pd = pd;
}

@Override
public void run() {
    try {
        con = new DatabaseConnection().getConnection();
        preparedStatement = con.prepareStatement("INSERT INTO customer_temp (C_ID, C_Name, C_Mob_No, C_City)                           VALUES (?,?,?,?)");
        System.out.println("Executing " + getName());
        while (rs.next()) {
            preparedStatement.setInt(1, rs.getInt(1));
            preparedStatement.setString(2, rs.getString("C_Name"));
            preparedStatement.setLong(3, rs.getLong("C_Mob_No"));
            preparedStatement.setString(4, rs.getString("C_City"));
            preparedStatement.addBatch();
            counter++;

            System.out.println("INSERT INTO Customer_Temp (C_ID, C_Name, C_Mob_No, C_City) VALUES('" + rs.getInt(1) + "','" + rs.getString(2) + "','" + rs.getInt(3) + "','" + rs.getString("C_City") + "')");

            if (counter % BATCH_EXECUTION_LIMIT == 0) {
                preparedStatement.executeBatch();
                System.out.println("After batch execution. . . .Counter :" + counter);
            }
        }
        if (counter % BATCH_EXECUTION_LIMIT != 0) {
            preparedStatement.executeBatch();
            System.out.println("Outer If...after batch execution. . . .Counter :" + counter);
        }
        //Thread.sleep(5000);
        pd.resume();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

}

请帮帮我.... 提前致谢

1 个答案:

答案 0 :(得分:0)

听起来根本不需要线程(一切都可以按照你自己的描述顺序运行)。因此,这不是您问题的直接答案,而只是对如何在程序中应用多线程的一般描述。

对于每个活动,声明一个实现Runnable的类。例如:

public class MyClass implements Runnable
{
    private String input  = null;
    private String output = null;

    public MyClass(String input)
    {
        this.input = input;
    }

    public String getOutput()
    {
        return output;
    }

    public void run()
    {
        output = func(input);
    }
}

在主活动中,启动所有线程,并等待每个线程仅在您实际需要其输出的位置完成。例如:

public String myFunc(String input) throws Exception
{
    MyClass object = new MyClass(input);
    Thread  thread = new Thread(object);

    thread.start();
    // Do whatever you wanna do...
    // ...
    // ...
    // And when you need the thread's output:
    thread.join();
    return object.getOutput();
}