在测试中,没有线程执行该方法

时间:2018-02-14 23:26:49

标签: java multithreading junit thread-safety

我有一个项目,但我看到了困难。 https://github.com/siqqQ/ILTasks/tree/master/busThread这是项目(4个文件)。我担心这个测试 `

void areAllPeopleWithDistinctTicket() throws InterruptedException {
    int numberOfPeople = 50;
    TicketManager t = TicketManager.getTicketManager(numberOfPeople);
    Set<Integer> persons = new HashSet<>();
    t.start();

    for (Person person : t.getPersons()) {
        if(!persons.add(person.getTicketNumber()) && person.getTicketNumber()!=null){
            fail("There are people with same tickets");
        }
    }
}

当我测试它时,它在控制台中显示我所有的门票都是SoldOut并且没有人在公共汽车上。 `

Name : Person 1 | Ticket: SoldOut
Name : Person 2 | Ticket: SoldOut
Name : Person 3 | Ticket: SoldOut
Name : Person 4 | Ticket: SoldOut
Name : Person 5 | Ticket: SoldOut
Name : Person 6 | Ticket: SoldOut
Name : Person 7 | Ticket: SoldOut
Name : Person 8 | Ticket: SoldOut
Name : Person 9 | Ticket: SoldOut
Name : Person 10 | Ticket: SoldOut
Name : Person 11 | Ticket: SoldOut
Name : Person 12 | Ticket: SoldOut...

`

如果有人能解释我为什么会这样,我会很高兴并为此提供一些解决方案。

1 个答案:

答案 0 :(得分:0)

TicketManager中,您无需等待线程完成执行即可调用printBusArrangment()。试试这个:

sendAllPeopleToBuyTicket(personsThreads, persons);
for (Thread thread : personThreads) {
    thread.join();
}
printBusArrangment(persons);