首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多线程Java如何使线程等待一段时间

多线程Java如何使线程等待一段时间
EN

Stack Overflow用户
提问于 2017-04-07 15:37:41
回答 2查看 1.4K关注 0票数 0

停车问题 有停车场。在一个停车场,一次只能有一辆车。如果所有的停车场都被占用了,那么这辆车将等待一段时间,如果仍然没有免费停车场,那么它就离开了。

它需要使用线程来解决(由will同步)。

这是我的密码:

停车场

代码语言:javascript
复制
class Parking implements Runnable {
private Thread thread;
private String threadName;
static int parkingLots;

static {
    parkingLots = 5;
}

Parking(String threadName) {
    this.threadName = threadName;
}

public void run() {
    if (parkingLots > 0) {
        long restTime = (long) (Math.random() * 2000);
        try {
            parkingLots--;
            System.out.println("Car " + threadName + " stands in the parking lot");
            Thread.sleep(restTime);
        } catch (InterruptedException e) {
        }
        parkingLots++;
        System.out.println("Car " + threadName + " has left parking, it stood there" + ((double)restTime / (double)1000) + " s");
    } else
        System.out.println("Car " + threadName + " has left parking");
}

public void start() {
    if (thread == null) {
        thread = new Thread(this, threadName);
        thread.start();
    }
}
}

代码语言:javascript
复制
public class Main {
    public static void main(String[] args) {
        ArrayList<Parking> parking = new ArrayList<Parking>();

        for (int i = 0; i < 15; i++) {
            parking.add(new Parking(String.valueOf(i + 1)));
        }
        for (Parking i: parking) {
            i.start();
        }
    }
}

我想看到的(当有2个停车场和4辆汽车时):

代码语言:javascript
复制
Car 1 stands in the parking lot
Car 2 stands in the parking lot
Car 3 is waiting
Car 4 is waiting
Car 3 has left parking
Car 2 has left parking, it stood there 1.08 s
Car 4 stands in the parking lot
Car 1 has left parking, it stood there 1.71 s
Car 4 has left parking, it stood there 0.83 s

但我得到的(当有2个停车场和4个汽车):所有的第一辆车(1和2)站在停车场,而其他(3和4)只是离开它,因为没有免费停车场。即使有15辆车,他们也进不去。

那么,我怎样才能让汽车等上一段时间才离开呢?如果有免费停车场,他们就会去,否则他们就会离开停车场。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-07 16:02:41

修改您的代码,看看这是否有效。

代码语言:javascript
复制
public class Parking implements Runnable {
    private Thread thread;
    private String threadName;
    static int parkingLots;

    static {
        parkingLots = 5;
    }

    Parking(String threadName) {
        this.threadName = threadName;
    }

    public void run() {
        long restTime = (long) (Math.random() * 2000);
        if (parkingLots > 0) {
            checkparking();
        } else {
            try {
                System.out.println("Car " + threadName + " is waiting");
                Thread.sleep(restTime);
                System.out.println("Car " + threadName + " is checking for free parkinglot");
                checkparking();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void checkparking() {
        if (parkingLots > 0) {
        long restTime = (long) (Math.random() * 2000);
        try {
            parkingLots--;
            System.out.println("Car " + threadName + " stands in the parking lot");
            Thread.sleep(restTime);
        } catch (InterruptedException e) {
        }
        parkingLots++;
        System.out.println(
                "Car " + threadName + " has left parking, it stood there" + ((double) restTime / (double) 1000) + " s");

    } else {
        System.out.println(
                "Car " + threadName + " has left since there is no parking space");
    }
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this, threadName);
            thread.start();
        }
    }

}

公共类Main {

代码语言:javascript
复制
     public static void main(String[] args) {
            ArrayList<Parking> parking = new ArrayList<Parking>();

            for (int i = 0; i < 15; i++) {
                parking.add(new Parking(String.valueOf(i + 1)));
            }
            for (Parking i: parking) {
                i.start();
            }
        }
}

产出:

代码语言:javascript
复制
Car 2 stands in the parking lot
Car 1 stands in the parking lot
Car 7 is waiting
Car 5 stands in the parking lot
Car 3 stands in the parking lot
Car 6 is waiting
Car 4 stands in the parking lot
Car 9 is waiting
Car 8 is waiting
Car 10 is waiting
Car 11 is waiting
Car 12 is waiting
Car 13 is waiting
Car 14 is waiting
Car 15 is waiting
Car 4 has left parking, it stood there0.049 s
Car 14 is checking for free parkinglot
Car 14 stands in the parking lot
Car 5 has left parking, it stood there0.366 s
Car 2 has left parking, it stood there0.461 s
Car 12 is checking for free parkinglot
Car 12 stands in the parking lot
Car 15 is checking for free parkinglot
Car 15 stands in the parking lot
Car 1 has left parking, it stood there0.882 s
Car 9 is checking for free parkinglot
Car 9 stands in the parking lot
Car 10 is checking for free parkinglot
Car 10 has left since there is no parking space
Car 3 has left parking, it stood there1.014 s
Car 13 is checking for free parkinglot
Car 13 stands in the parking lot
Car 15 has left parking, it stood there0.937 s
Car 6 is checking for free parkinglot
Car 6 stands in the parking lot
Car 11 is checking for free parkinglot
Car 11 has left since there is no parking space
Car 13 has left parking, it stood there0.344 s
Car 7 is checking for free parkinglot
Car 7 stands in the parking lot
Car 8 is checking for free parkinglot
Car 8 has left since there is no parking space
Car 7 has left parking, it stood there0.054 s
Car 14 has left parking, it stood there1.731 s
Car 9 has left parking, it stood there1.359 s
Car 12 has left parking, it stood there1.877 s
Car 6 has left parking, it stood there1.787 s
票数 2
EN

Stack Overflow用户

发布于 2017-04-07 16:28:05

您没有使用和同步,您的类不应该实现Runnable,而且您使用的语义也不正确。

例如,在启动cars不能停车/离开之后,多线程是指多线程同时被多个线程访问,而不是导致不一致的状态,在您的情况下,您基本上只是创建线程和做一些事情。

你的结构应该是这样的:

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Parking  {

    private final Lock monitor = new ReentrantLock();
    private final Condition lotAvailable = monitor.newCondition();

    private List<Car> parkedCars = new ArrayList<>();

    private final int maxCapacity;
    private int occupied;

    public Parking(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

    private boolean tryPark(Car car, int maxWaitingMillis) throws InterruptedException{
        try {
            monitor.lock();
            if(occupied >= maxCapacity){
                long nanos = lotAvailable.awaitNanos(maxWaitingMillis);
                while (occupied >= maxCapacity) {
                    if (nanos <= 0L)
                        return false;
                    nanos = lotAvailable.awaitNanos(nanos);
                }
                ++occupied;
                parkedCars.add(car);
                return true;
            }
            ++occupied;
            parkedCars.add(car);
            return true;
        }catch (InterruptedException ie){
            System.out.println(ie.getMessage());
            throw ie;
        }finally {
            monitor.unlock();
        }

    }

    private void leave(Car car){
        try {
            monitor.lock();
            if(parkedCars.remove(car)) {
                --occupied;
                lotAvailable.signal();
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            monitor.unlock();
        }
    }


}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43282088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档