Java concurrency using Scheduledexecutor's greenhouse controller--thinking in Java 21.7.5

Source: Internet
Author: User
Tags dateformat

Package Org.rui.thread.newc;import Java.text.dateformat;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.calendar;import Java.util.collections;import Java.util.List;import Java.util.random;import Java.util.concurrent.scheduledthreadpoolexecutor;import java.util.concurrent.TimeUnit;/* * * Greenhouse Controller * @author Lenovo * */public Class greenhousescheduler{private volatile Boolean light = false;//Optical Private Volat Ile Boolean water = false;//Water private String thermostat = "Day";//Thermostat public synchronized String Getthermostat () {return Thermostat;} Public synchronized void Setthermostat (String thermostat) {this.thermostat = thermostat;} Scheduler Scheduledthreadpoolexecutor Scheduler = new Scheduledthreadpoolexecutor,/** * * @param event * @param delay Delay */public void Scheduler (Runnable event, long delay) {/** * builds and executes a one-time operation enabled after a given delay. */scheduler.schedule (event, delay, timeunit.milliseconds);} /** * Repeat * @param envent * @param initialdelay * @param the less cycle time between successive executions of periodThe faster you execute */public void repeat (Runnable envent, long initialdelay, long period) {/** * Creates and executes a recurring operation that is first enabled after the given initial delay, and the subsequent operation has a given period; It will be executed after InitialDelay *, then executed after Initialdelay+period, then executed after InitialDelay + 2 * period, and so on. */scheduler.scheduleatfixedrate (Envent, InitialDelay, period,timeunit.milliseconds);} /** * Inner class * Turn on Lights */class Lighton implements runnable{//put hardware control code here to put hardware control codes here//physically Turn on the light. Body turn on the light. @Overridepublic void Run () {//system.out.println ("Turning on Lights"); System.out.println ("Turn on the lamp"); light = True;}} /** * off * @author Lenovo * */class Lightoff implements runnable{//put hardware control code here to put hardware control codes here//physical Ly turn off the light. Turned off the light. @Overridepublic void Run () {System.out.println ("Turn Off Light"),//system.out.println ("Turning off"); water = True;}} Class Wateron implements runnable{@Overridepublic void Run () {//system.out.println ("Turning Greenhouse Water on"); System.out.println ("Greenhouse water Open"); water = True;}} Class Wateroff ImplemenTS runnable{@Overridepublic void Run () {System.out.println ("Greenhouse water off")//system.out.println ("Turning Greenhouse water off "); water = false;}} /** * Thermostat Night * @author Lenovo * */class Thermostatnight implements runnable{@Overridepublic void Run () {//Put hardware Co Ntrol code here//SYSTEM.OUT.PRINTLN the hardware control codes ("Thermostat to Night setting"); SYSTEM.OUT.PRINTLN ("Automatic thermostat Night Setting"); Setthermostat ("Night");}} /** * Daytime * @author Lenovo * */class Thernostatday implements runnable{@Overridepublic void Run () {//Put hardware control C Ode HereSystem.out.println ("Greenhouse daytime setting"),//system.out.println ("Thermostat to day Setting"); Setthermostat ("Days");}} /** * Clock * @author Lenovo * */class Bell implements runnable{@Overridepublic void Run () {System.out.println ("bing! bells >> ");}} /** * Termination * @author Lenovo * */class Terminate implements runnable{@Overridepublic void Run () {System.out.println ("Terminate Scheduler.shutdown ();//must start a separate task to does this job must start a separate task to do the job//since the scheduler has been ShUT down self-scheduler has closed new Thread () {public void run () {Datapoint d:data) {System.out.println ("Datapoint:" +d);}};}. Start ();}} /** * can hold and display individual data segments * @author Lenovo * *///Inner class static class datapoint{final Calendar time;final float temperature Final float humidity;/** * @param time * @param temperature * @param humidity */public datapoint (Calendar time, float tem Perature, float humidity) {this.time = Time;this.temperature = temperature;this.humidity = humidity;} Public String toString () {DateFormat fd=new SimpleDateFormat ("YYYY/MM/DD hh:mm ss"); return Fd.format (Time.gettime ()) + String.Format ("temperature:%1$.1f humidity:%2$.2f", temperature, humidity);}} Private Calendar Lasttime = Calendar.getinstance (); {///adjust data to the half hour adjusted for half an hour Lasttime.set (Calendar.minute, +); Lasttime.set (Calendar.second, 00);}  private float lasttemp = 65.0f;//private int tempdirection = +1;//temperature azimuth private float lasthumidity = 50.0f;//last Humidity private int humiditydirection = +1;//Moisture Azimuth private Random RAnd = new Random (47); list<datapoint> data = collections.synchronizedlist (new arraylist<datapoint> ());//dispatched task, which, at each run, can generate simulation data and add it to Greenhouse's list<datapoint>//Ineer Classclass Collectdata implements runnable{@ overridepublic void Run () {System.out.println ("Collectdata" "Run"); synchronized (greenhousescheduler.this) {// Pretend the interval is longer than it is: pretend time interval ratio is: Lasttime.set (Calendar.minute,lasttime.get (calendar.minute) +);//O NE in 5 chances of reversing the direction: an opportunity to reverse direction in 5: if (Rand.nextint (5) = = 4) {tempdirection =-tempdirection;//direction}// Store previous value: Store previous value: lasttemp = lasttemp + tempdirection * (1.0f + rand.nextfloat ()); if (Rand.nextint (5) = = 4) {Humi Ditydirection =-humiditydirection;} lasthumidity = lasthumidity + humiditydirection* rand.nextfloat ();//calendar must be cloned, otherwise all//datapoints Hold references to the same lasttime.//for a basic object like Calendar,clone () is Ok.data.add (new Datapoint ((Calendar) L Asttime.clone (), lasttemp,lasthumidity));}}}  Mainpublic static void Main (string[] args) {greenhousescheduler gh = new Greenhousescheduler ();//delay How much time Close Gh.scheduler (gh.new Terminate (), ();//Former restart class not necessary: Pre-restart class not necessary: Gh.repeat (Gh.new Bell (), 0, 1000 );//Bell Gh.repeat (Gh.new thermostatnight (), 0, 2000);//night 2 seconds Execution Gh.repeat (gh.new Lighton (), 0, 200);//Lamp Gh.repeat (gh.new Lightoff (), 0, Gh.repeat (gh.new Wateron (), 0, 600);//Water gh.repeat (gh.new wateroff (), 0, +);//Gh.repeat (Gh.new the Rnostatday (), 0, 1400);//Daytime Gh.repeat (Gh.new collectdata (), 500, 500);}} /*** * Output: * bing! Bell >> automatic thermostat night set turn on lights turning off light greenhouse water open greenhouse water switch greenhouse day setting turn on electric light turn off light collectdata "" Run greenhouse water open electric light turn off light greenhouse water off ing! Bell >> turn on the Electric Light Collectdata "" Run turn on the electric light greenhouse water turn off light turn off the lamp greenhouse daytime setting collectdata "Run turn on the electric light greenhouse water turn off the light turn off lights open the lamp greenhouse water Open bing! Bell >> Collectdata "" Run turn off the light turn off the lamp automatic thermostat night set turn on the electric light turn off the light greenhouse water open greenhouse water off Collectdata "" Run turn on the electric light turn off the light greenhouse daytime set open electric Light Collectdata "" Run greenhouse water bing! Bell >> turn off light greenhouse water off turn on electric light Collectdata "" Run turn off light greenhouse water startTurn on the Electric light bing! Bell >> automatic thermostat night set turn off the lights greenhouse Water Collectdata "" Run turn on the light bulb open the lamp greenhouse water open greenhouse daytime set turn off light collectdata "" Run turn on the lights turn on the lights greenhouse water turn off the turn off the lights bing! Bell >> turn on the Lights Collectdata "" Runterminate "" End Datapoint:2015/07/19 00temperature : 66.4 humidity:50.05datapoint:2015/07/19 09:30 00temperature:68.0 humidity:50.47datapoint:2015/07/19 10:00 00temperature:69.7 HUMIDITY:51.42DATAPOINT:2015/07/19 00temperature:70.8 HUMIDITY:50.87DATAPOINT:2015/07/19 11:00am 00temperature:72.0 humidity:50.32datapoint:2015/07/19 00temperature:73.2 humidity:49.92datapoint:2015/ 07/20 00temperature:71.9 humidity:49.81datapoint:2015/07/20 00temperature:70.1 humidity:50.25DataPoint : 2015/07/20 01:00 00temperature:68.9 humidity:51.00datapoint:2015/07/20 01:30 00temperature:67.7 humidity:50.21 * *


Java concurrency using Scheduledexecutor's greenhouse controller--thinking in Java 21.7.5

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.