现在我有10000条数据,我要分批处理这10000条数据,我开了2个线程,我想第一个线程处理前5000条,第二个线程处理后5000,怎样写这个代码。有没有列子啊。
现在的代码
 while (object.next())  {
             threadA.run();
             threadb.run();
             }
现在2个线程同时处理一个数据,没有效果。该怎样改,请假高手。

解决方案 »

  1.   

    分别处理5000条,应该分别从数据库选择5000条的结果集交给两个线程处理,否则就只能两个线程交替处理,不保证前后5000条,比如
    class RunThread extends Thread {
        ResultSet rs;
        public RunThread(ResultSet rs) {this.rs = rs;}
        public void run() {
            while (true) {
                synchronized(rs) {
                    if (rs.next()) {
                        //get data from rs
                    } else {
                        break;
                    }
                }
                //do something with your date
                yield();
            }
        }
    }
    //主程序
    ResultSet rs = get_your_resultset
    Thread a = new RunThread(rs);
    Thread b = new RunThread(rs);
    a.start();
    b.start();
      

  2.   

    通过一个方法截取前5000条数据和后5000条数据,然后按照下面的方式处理。
    package test;import java.util.ArrayList;
    import java.util.List;/**
     * 有10000条数据,要分批处理这10000条数据,我开了2个线程,我想第一个线程处理前5000条,第二个线程处理后5000
     * @author 0012354
     * 
     */
    public class C
    {
        public static void main(String[] args)
        {
            List<String> list1 = new ArrayList<String>();
            list1.add("1");list1.add("2");list1.add("3");
            List<String> list2 = new ArrayList<String>();
            list2.add("11");list2.add("22");list2.add("33");
            
            new ThreadTest(list1).start();
            new ThreadTest(list2).start();
        }
    }class ThreadTest extends Thread
    {
        private List<String> list;
        public ThreadTest(List<String> list)
        {
            this.list = list;
        }
        
        public void run()
        {
            while(true)
            {
                String s = null;
                synchronized(list)
                {
                    if(list.size() == 0)
                    {
                        return;
                    }
                    s = list.remove(0);
                }
                
                s = (null == s) ? "null" : s;
                System.out.println("Thread=" + Thread.currentThread().getName()+ ", s=" + s);
            }
        }
    }
      

  3.   

    顶四楼,不能用rs.next()了,必须把结果集截成两段,用LIST容器装起来,这样多线程才有效果,否则是线程同步,这里又不需要线程同步。
      

  4.   

    如果用List,我这里说的是10000条数据,但是这个数据有变,不确定,我怎样平分数据呢?