gpt4 book ai didi

java - Java中无法同步线程(使用信号量)

转载 作者:行者123 更新时间:2023-12-01 19:17:53 25 4
gpt4 key购买 nike

美好的一天!

我遇到了同步线程的问题。我正在编写类似于哲学家晚餐的程序。我的进程(例如 3 个)和资源(例如 4 个)很少。每个进程只能使用 2 个可用资源。这意味着第一个进程只能使用第一个和第二个资源等。

我决定使用信号量来实现我的目标。问题是仍然没有同步。例如,如果第一个和第三个进程正在使用资源,那么第二个进程必须等待,直到他的资源不会被释放。在我的程序中有时会发生...有时不会。

有什么问题吗?我该如何解决这个问题?

代码在这里:

public class Sem
{
public Sem()
{
available = new ConcurrentHashMap< Integer, Semaphore >();//Resources.

for ( int i = 1; i <= 4; i++)
{
available.put( i, new Semaphore(1, true) );//Each resource contains semaphore.
}
}

public void start( final int id )
{
thisThread = new Thread()
{
public void run()
{
try
{
work( id ); //Try to take resourses.
Thread.currentThread().sleep(1000);
release( id ); //Release resources.
} catch (InterruptedException ex) {
Logger.getLogger(Sem.class.getName()).log(Level.SEVERE, null, ex);
}

}
};
thisThread.start();
}

public synchronized void work( int id ) throws InterruptedException
{
available.get(id).acquire(); //Try to take resourse[id] and resourse[id+1]
available.get(id+1).acquire(); //Thread is blocking till it will be possible.

System.out.printf("Acquired [%s], id = %d\n",Thread.currentThread().getName(), id);

}

public void release( int id )
{
available.get(id).release(); //Release resources which hava been captured by thread.
available.get(id+1).release(); //After this other thread can take these resourses.

System.out.printf("Released [%s], id = %d\n",Thread.currentThread().getName(), id);
}


private ConcurrentHashMap< Integer, Semaphore > available; //Integer - id of thread[1..4]; Semaphore - is gate with param (1)
//Available - map of resources which can be busy by processes.
Thread thisThread;
}

我这样启动这个程序:

Sem sem = new Sem();

sem.start(1);
sem.start(2);
sem.start(3);

我的输出消息很少,但我最喜欢的是:

Acquired [Thread-1], id = 1
Acquired [Thread-3], id = 3
Released [Thread-1], id = 1
Acquired [Thread-2], id = 2
Released [Thread-3], id = 3
Released [Thread-2], id = 2

流程 2 开始工作,而他却做不到!!

最佳答案

我认为您应该以与获取锁相反的顺序释放锁。

关于java - Java中无法同步线程(使用信号量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5764578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com