简体   繁体   中英

get ScheduledExecutorService to change a variable to 3 different values

Im having task where im asked to make a server program on java that accepts multiple clients. The server program is going to do nothing more than simulate a traffic light. Connecting the client to the server program is not my issue. But to have some kind of scheduler with the following properties:

-Returns a String that says "Red" for 5 sec, "Yellow" for 2 seconds and then "green" for 10 seconds.(repeat)

Depending on when you connect to the server you will get back one of this colors as if it was a real traffic light.

my problem is wrapping my head around ScheduledExecutorService. Im not a very experienced programmer, so any explanation around this would be highly appreciated.

Excuse me if my question is hard to understand. Thank you so much in advance! :)

This link might show how to use ScheduledExecutorService :

https://github.com/csrg-utfsm/acscb/blob/master/ACS/LGPL/CommonSoftware/jacsutil/src/alma/acs/concurrent/ThreadLoopRunner.java#L137

public ThreadLoopRunner(Runnable task, long delayTime, TimeUnit unit, final ThreadFactory tf, Logger logger, String name) {
    this.logger = logger;
    this.loopName = ( (name != null && !name.trim().isEmpty()) ? name.trim() : null );

    this.runner = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(tf, loopName));

    this.taskWrapper = new TaskWrapper(task, loopLock, logger);
    this.delayMode = ScheduleDelayMode.FIXED_RATE;
    isDefunct = new AtomicBoolean(false);
    setDelayTime(delayTime, unit);
}

You can find some ideas in the following code (from code.openhub.net):

public void start() {
    multicastService.get().start();
    udpService.get().start();
    connectionDispatcher.get().addConnectionAcceptor(this, false, "CONNECT", "\n\n");
    backgroundExecutor.scheduleWithFixedDelay(incomingValidator,
            timeBetweenValidates, timeBetweenValidates,
            TimeUnit.MILLISECONDS);
    _started = true;
}

http://code.openhub.net/file?fid=fPRP5s8NPWNQmdQRgi2Cl5Gh5as&cid=gm3VRNBX7Kw&s=get%20ScheduledExecutorService%20to%20change%20a%20variable%20to%203%20different%20values&pp=0&fl=Java&ff=1&filterChecked=true&fp=4419&mp,=1&ml=0&me=1&md=1&projSelected=true#L0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM