【发布时间】:2021-01-10 22:02:18
【问题描述】:
我为 2 列火车创建了 2 个线程,第一个有 (nord-sud) 方向,第二个有 (sud-nord) 方向,所以只有一条铁路,不能满足 2 列不同方向的火车.. 所以这是我的主要课程:
public static void main(String[] args) throws InterruptedException {
Semaphore sem = new Semaphore(1);
MyThread train1 = new MyThread(sem, "nord-sud");
MyThread train2 = new MyThread(sem, "sud-nord");
// stating threads 1 and train 2
train1.start();
train2.start();
train1.join();
train2.join();
}
这是我的 MyThread 类扩展的 Thread 类:
class MyThread extends Thread
{
Semaphore sem;
String threadName;
public MyThread(Semaphore sem, String threadName)
{
super(threadName);
this.sem = sem;
this.threadName = threadName;
}
@Override
public void run() {
// run by thread A
if(this.getName().equals("nord-sud"))
{
System.out.println("Starting " + threadName);
try
{
System.out.println(threadName + " wait for railway to enter");
// acquiring the lock
sem.acquire();
System.out.println(threadName + " have access to enter");
// Now, accessing the shared resource.
// other waiting threads will wait, until this
// thread release the lock
for(int i=0; i < 5; i++)
{
Shared.count++;
System.out.println(threadName + ": " + i);
// Now, allowing a context switch -- if possible.
// for thread B to execute
Thread.sleep(1000);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
// Release the permit.
System.out.println(threadName + " left the railway ");
sem.release();
}
// run by thread B
else
{
System.out.println("Starting " + threadName);
try
{
// First, get a permit.
System.out.println(threadName + " wait for railway to enter");
sem.acquire();
System.out.println(threadName + " have access to enter");
for(int i=0; i < 5; i++)
{
Shared.count--;
System.out.println(threadName + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
// Release the permit.
System.out.println(threadName + "left the railway");
sem.release();
}
}
}
因此,当我在同一时期添加 2 列北南方向的火车时,我希望它们都进入铁路,因为它们具有相同的方向,只有当他意识到另一列不同方向的火车时,火车才应该等待是在铁路。那么我怎样才能同时执行 2 个线程呢?例如 train1(nord-sud)、train2(nord-sud) 和 train3(sud-nord)。所以火车 1 和火车 2 都进入铁路,火车 3 等他们离开才能进入。
【问题讨论】:
-
为什么是
if... else...块?您在两个分支中运行完全相同的代码。
标签: java multithreading semaphore