gpt4 book ai didi

java - 变量的互斥不起作用

转载 作者:行者123 更新时间:2023-12-02 09:40:35 25 4
gpt4 key购买 nike

我试图模拟游客进入剧院并占据一个可用的座位(可用座位的数量是共享的),一旦所有座位都被占用,其余的就去 sleep 。我在访问者类中的 getsit 方法中的 availablesits 变量上遇到问题。请帮助我

我尝试同步线程以及使变量可变。但由于某些原因,所有线程同时到达 getsit 部分?我不明白为什么!//主要

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int numVisitors = 23;
int theaterCapacity =5;
int party_ticket=3;
Clock clock = new Clock();
Theater theater=new Theater(theaterCapacity,clock);
ArrayList<Visitor> visitorlist = new ArrayList<Visitor>();
for(int i=1;i<=numVisitors;i++) {
visitorlist.add(new Visitor(i,clock,theater));
}
clock.start();
for(Visitor visitor:visitorlist)
visitor.start();

}
}

//访问者类别

  public class Visitor extends Thread{


private static Clock clock;
private static Theater theater;
public int id;
public boolean sawPresentation=false;
public volatile int priority= 10;
public static long time = System.currentTimeMillis();
public void msg(String m) {
System.out.println("["+(System.currentTimeMillis()-time)+"] "+getName()+": "+m);
}
Visitor(int id, Clock clock, Theater theater){
this.id=id;
this.clock=clock;
this.theater=theater;
}
public void run(){
heArrives();
while(!sawPresentation) {
while(!clock.presentationIsOpen()) {
//busy wait
}
getASit();
}
}
public void heArrives() {
msg("the visitor arrived");
}
public synchronized void getASit(){
if(theater.availableSits>0){
msg("the visitor got a sit");
theater.availableSits--;
watchPresentation();
}
}
public void watchPresentation(){
msg("the visitor is watching the presentation");
}
}

//时钟类

import java.util.Timer;
import java.util.TimerTask;
public class Clock extends Thread {
public static long time = System.currentTimeMillis();
public static int secondsPassed=6;
Timer timer= new Timer();

TimerTask task = new TimerTask() {
@Override
public void run() {
secondsPassed++;
//System.out.println("seconds passed: "+secondsPassed);
}
};
public void run(){
timer.scheduleAtFixedRate(task,0,1000);
}
public boolean presentationIsOpen(){
if(secondsPassed%6==0) return true;
return false;
}
}

//戏剧课

class Theater extends  Thread{
public static Clock clock;
public int capacity;
public volatile int availableSits=5;
Theater(int capacity,Clock clock){
this.capacity=capacity;
this.clock=clock;
}
}

最佳答案

您的主要问题是 getASit 方法的同步。您正在与 Visitor 对象实例进行同步,因此每个线程都针对不同的对象进行同步。相反,您必须与共享的对象同步。在你反对剧院的情况下。将您的方法更改为如下所示:

 public   void getASit(){
synchronized(theater){
if(theater.availableSits>0){
msg("the visitor got a sit");
theater.availableSits--;
watchPresentation();
}
}
}

最好不要使用busy wait,太烧cpu了,最好使用sleep之类的:

while(!clock.presentationIsOpen()) {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

关于java - 变量的互斥不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103257/

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