gpt4 book ai didi

java - 使用 wait/notify 创建 Event 类

转载 作者:行者123 更新时间:2023-12-01 05:11:33 25 4
gpt4 key购买 nike

这是一道考试题,我以前考得不好,但这次我想把它做好。如果有人能给我指出正确的方向,我将不胜感激,谢谢。

我的问题是,所提供的解决方案是否能正确解决问题?如何改进。

我的代码遵循问题。

问题:

An event object has one of two states signaled or non-signaled. When the event is in the signaled state all or one waiting threads are released. When it is reset to the non-signaled state all the user threads will be forced to wait. An event stays in the signaled state until it is reset to the non-signaled state. The basic idea is that one or more threads can wait for some event to happen. When the event waited for occurs the threads take whatever action is required. Using wait/notify write an Event class.

我的尝试:

class Event  {
boolean signal;
String obj = new String();

public Event(boolean signal) {
this.signal = signal;
}
synchronized void getSignal(){
while(!signal)
try{
wait();
}
catch(InterruptedException e) {}
}
public void setSignal(boolean signal) {
synchronized (this) {
this.signal = signal;
this.notifyAll();
}
}
}

最佳答案

我做了这个测试类,我认为它回答了这个主题,并且我的 Activity 在某种程度上与你的类似。

一个线程正在等待事件发生(收到信号时),然后在另一个线程不时激活和停用信号时等待重置。

编辑:我不知道你的简单问题,所以也许这段代码对你来说没有用。不管怎样,你的 Event 类应该可以工作,所以我能说什么?

public class SynchronizationTest {

public class Event {

boolean signal = false;
synchronized String getEvent(){
while(!signal) {
try{
wait();
}
catch(InterruptedException e) {}
}
return "This is an event";
}

synchronized public void waitNextEvent(){
while(signal) {
try{
wait();
}
catch(InterruptedException e) {}
}
}

synchronized public void setSignal(boolean signal) {
this.signal = signal;
this.notifyAll();
}
}

class EventChecker extends Thread {

private Event event;
public EventChecker(Event event) {
this.event=event;
}

public void run(){
while (true) {
String eventStr = event.getEvent();
System.out.println("EventChecker: Got event '"+eventStr+"'");
System.out.println("EventChecker: wait for new event.. \n");
event.waitNextEvent();
}
}
}

class EventSignaler extends Thread {

private Event event;
public EventSignaler(Event event) {
this.event=event;
}

public void run(){
while (true) {
event.setSignal(true);
System.out.print("EventSignaler: Sending new signal\n");
try {
sleep((int) (Math.random()*2200));
} catch(Exception e){}

event.setSignal(false);
System.out.print("EventSignaler: Deactivating signal\n\n");
try {
sleep((int) (Math.random()*4200));
}
catch(Exception e){}
}
}
}

public void startTest() {

Event event=new Event();
EventSignaler eventSignaler = new EventSignaler(event);
EventChecker eventChecker=new EventChecker(event);
eventSignaler.start();
eventChecker.start();
}

public static void main(String arg[]) {

SynchronizationTest synchro = new SynchronizationTest();
synchro.startTest();
}
}

关于java - 使用 wait/notify 创建 Event 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979704/

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