为 运行 算法玩家创建线程
Creating threads to run algorithm players
我正在尝试编写一个程序来实现 Prisoners and switches problem 的解决方案。我创建了一个 SwitchRoom class..
public class SwitchRoom
{
private boolean switchA;
private boolean switchB;
和一名囚犯class
public class Prisoner
{
public void visitSwitchRoom() {
// do something with switches
现在我在想我如何才能做到这一点运行。最好让 Prisoner class 实现 Runnable(将它们的实例变成线程),然后在 java 程序中生成 23 个线程吗?
如果这是一个好方法,能否提供一个代码示例让我开始?
如果方法不对,你能给我一些指导吗?
你的理论化方法似乎没问题。
从实现runnable开始,在run()
方法中做:
public void run() {
while (true) {
if (/*counterperson has 23 counts*/) { break; }
synchronized (/*your switchroom object here*/) { // this makes it so only one person can flip switches at a time
// use an if/else to figure out if this person is the "counter" person
// try to flip a switch/do stuff based on required logic regarding if he is
// the counter person
}
try {
wait(100); // or however long you want to wait before trying again
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
并创建 23 个这样的线程。如果你在每个对象中放置一个布尔值来表示该对象是普通囚犯还是柜台人员,请记住将默认设置为 false,并将其中一个设置为 true,以便最终跳出 while 循环。
我正在尝试编写一个程序来实现 Prisoners and switches problem 的解决方案。我创建了一个 SwitchRoom class..
public class SwitchRoom
{
private boolean switchA;
private boolean switchB;
和一名囚犯class
public class Prisoner
{
public void visitSwitchRoom() {
// do something with switches
现在我在想我如何才能做到这一点运行。最好让 Prisoner class 实现 Runnable(将它们的实例变成线程),然后在 java 程序中生成 23 个线程吗?
如果这是一个好方法,能否提供一个代码示例让我开始?
如果方法不对,你能给我一些指导吗?
你的理论化方法似乎没问题。
从实现runnable开始,在run()
方法中做:
public void run() {
while (true) {
if (/*counterperson has 23 counts*/) { break; }
synchronized (/*your switchroom object here*/) { // this makes it so only one person can flip switches at a time
// use an if/else to figure out if this person is the "counter" person
// try to flip a switch/do stuff based on required logic regarding if he is
// the counter person
}
try {
wait(100); // or however long you want to wait before trying again
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
并创建 23 个这样的线程。如果你在每个对象中放置一个布尔值来表示该对象是普通囚犯还是柜台人员,请记住将默认设置为 false,并将其中一个设置为 true,以便最终跳出 while 循环。