如何在java中限制while循环?

时间:2016-12-13 15:14:04

标签: java multithreading while-loop

我使用线程创建了名为Single Lane Bridge的程序,其中单线桥连接North Village和South Village。两个村庄的农民使用这座桥将产品运送到邻近的城镇。如果北向和南向的农民同时上桥,这座桥就会陷入僵局(这些村庄的农民很顽固,无法支援)。

我正在尝试两个限制正在创建的成帧器的数量只有2.并且一旦两个农民都已经越过我希望程序结束。目前程序仍在运行,

以下是我对上述问题的解决方案。

echo "Renaming database file produced by previous test run"
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string

1 个答案:

答案 0 :(得分:0)

这是修改,跟踪所有过桥的农民。

package multithreading1;

import java.util.concurrent.TimeUnit;

public class SingleLaneBridge {

    // count of all farmers
    private volatile static int count = 0;
    // variable used for synchronization in multiple threads
    private static final Integer max_count = 2;

    public static void main(String[] args) {
        final Bridge bridge = new Bridge();

        Thread thNorthbound = new Thread(new Runnable() {

            @Override
            public void run() {

                while (true) {
                    Farmer farmer = new Farmer(bridge);
                    // tracking count of farmers in multiple threads
                    synchronized (max_count) {
                        count++;
                        if (count > max_count)
                            break;
                        farmer.setName("North Farmer " + count);
                    }

                    Thread th = new Thread(farmer);
                    th.start();

                    try {
                        TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
                    } catch (InterruptedException iex) {
                        iex.printStackTrace();
                    }
                }

            }
        });

        Thread thSouthbound = new Thread(new Runnable() {

            @Override
            public void run() {

                while (true) {
                    Farmer farmer = new Farmer(bridge);
                    // tracking count of farmers in multiple threads
                    synchronized (max_count) {
                        count++;
                        if (count > max_count)
                            break;
                        farmer.setName("South Farmer " + count);
                    }

                    Thread th = new Thread(farmer);
                    th.start();

                    try {
                        TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
                    } catch (InterruptedException iex) {
                        iex.printStackTrace();
                    }
                }
            }
        });

        thNorthbound.start();
        thSouthbound.start();
    }

}