2

Here it is the problem I am trying to solve but not sure how to do it: I have an array of objects (say size is 100) and each object has some id.

Class Employee{
   int EmployeeId;
}

There are 10 threads which will read data from this array and insert it into database.

How to make sure data is inserted into DB based on the sequence of EmployeeId in increasing sequence. For example:

If array has objects with EmployeeID 6, 8 and 4, then these objects should be inserted in DB in sequence of EmployeeID 4,6,and 8 in DB. How to write multi-threaded code for this?

UPDATE: Please ignore DB part, if it is confusing, My main intention is to process concurrently but in sequence.

4

2 回答 2

5

我认为您不了解此处使用线程。线程1用于并行任务(可能除了一些障碍)排序无关紧要并且您的线程并行运行。您需要一个简单的循环或其他类型的串行行为。

您可以使用一个线程轻松完成此操作。你可以在这里走安全的道路。线程不保证任何关于优化和排序的事情。如果预处理很昂贵,请以线程方式进行,然后确保线程全部以 a 结束CountdownLatch,然后插入数据库。

1穿线可导致死亡、窒息、寒战、发烧、溺水、感染、恶心和无法控制重型机械

于 2013-09-06T14:55:44.717 回答
2

如果我理解正确,您必须为数组的每个条目按顺序执行一些任务(我假设 10 个)。

首先,您需要在一个实现的类中按顺序组织这 10 个任务Runnable

public class ThreadedTask implements Runnable {
    private Employee employee;
    public ThreadedWork(Employee employee) {
        this.employee = employee;
    }
    public void executeTaskList(Employee employee) {
        task1(employee);
        task2(employee);
        // ...
        task10(employee);
    }
    public void run() {
        executeTaskList();
        notify();
    }
}

然后,您可以实施以下解决方案之一:

  1. 在数组中插入Employee对象,创建一个ThreadedTask对象并在线程上调用它的执行。
  2. 将所有Employee对象插入数组中,然后使用for循环创建ThreadedTask对象并在线程上调用其执行。

我将在这里为选项 2 写一个简单的建议:

/*
 * I am assuming that there`s an array called empArray, which holds 100 employees.
 * It's up to you to decide how it is populated.
 */
public void processEmployees() {
    // ...
    for(Employee e : empArray) {
        (new Thread(new ThreadedTask(e))).start()
    }
    // ...
}

如您所见,逻辑分为两部分:由您来定义empArray填充方式以及ThreadedTask对象的创建和执行方式。但是 对于每个对象按顺序ThreadedTask执行任务列表。Employee

请注意,无法判断Employee在任何给定时刻处理了哪个对象。所有员工都是同时处理的,但每个员工的任务是按顺序执行的。

希望这可以帮助

于 2013-09-06T15:49:21.180 回答