質問

I made ​​a clock in java that shows the current time. I would make sure that the clock both updated at intervals of one minute, thus updating the result in the console. I read to use threads, but I'm not very knowledgeable on the subject, who would help me to make it happen?

import java.util.*;

public class Current
{
  public static void main(String[] args)
  {
      Calendar calendar = new GregorianCalendar();
      String hour;
      int time = calendar.get(Calendar.HOUR);
      int m = calendar.get(Calendar.MINUTE);
      int sec = calendar.get(Calendar.SECOND);

      if(calendar.get(Calendar.AM_PM) == 0)
          hour = "A.M.";
      else
          hour = "P.M.";
      System.out.println(time + ":" + m + ":" + sec + " " + hour);
  }
  }

     class Data
     {
     public static void main(String[] args)
     {
     Calendar cal = new GregorianCalendar();
     int day = cal.get(Calendar.DAY_OF_MONTH);
     int month = cal.get(Calendar.MONTH);
     int year = cal.get(Calendar.YEAR);
     System.out.println(day + "-" + (month + 1) + "-" + year);
     }
     }
役に立ちましたか?

解決

public static void main(String[] args) {
    while (true) {
        try {
            Thread.sleep(60*1000); //one minute

            Calendar calendar = new GregorianCalendar();
            String hour;
            int time = calendar.get(Calendar.HOUR);
            int m = calendar.get(Calendar.MINUTE);
            int sec = calendar.get(Calendar.SECOND);

            if(calendar.get(Calendar.AM_PM) == 0)
                hour = "A.M.";
            else
                hour = "P.M.";
            System.out.println(time + ":" + m + ":" + sec + " " + hour);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

他のヒント

Try with SimpleDateFormat that is more easy to format the date.

Sample code

final SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a");
new Thread(new Runnable() {

    @Override
    public void run() {
        while (true) {
            System.out.println(format.format(new Date()));
            try {
                Thread.sleep(60 * 1000);//60 seconds interval
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}).start();

Note: It might generate correct result but not accurate always.

The other answers are outdated on two counts:

  • The old date-time classes such as Date & Calendar & SimpleDateFormate are now legacy, supplanted by the java.time classes.
  • Java now offers a more sophisticated way to schedule a regular background task: The Executor framework such as the ScheduledExecutorService. The Timer class documentation suggests using this newer approach in its stead.

Here is an example, ready to run. Both the ScheduledExecutorService and the java.time classes are discussed in many other Questions. Search Stack Overflow for more discussion.

In a nutshell, the ScheduledExecutorService is responsible for running your desired task every so often. You may ask for every minute, but remember that it may not be exactly every minute on a conventional implementation of Java (you would need a real-time Java implementation to be precise). Here we have told our executor to use a pool of a single background thread to run our task of telling the time. The one trick here is that any Exception reaching the ScheduledExecutorService will cause the scheduling to cease, silently with no comment or warning. So be sure your task code is always nested in a try-catch as shown and commented in this example below.

For telling the time, we capture the current moment in a particular time zone. We then create a string to represent that moment. I suggest letting java.time automatically localize such strings, as shown in the commented-out code. But here, per the Question, we generate a string with an AM/PM time-of-day only format. Here is a shortened version of the code seen in the example further down.

ZoneId zoneId = ZoneId.of ( "America/Montreal" ); // Desired/expected time zone. Always specify the zone; Never depend on the JVM’s current default as it can change at any moment.
ZonedDateTime zdt = ZonedDateTime.now ( zoneId );  // Capture the current moment for that time zone.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "hh:mm:ss a" , Locale.US );  // Format the time-of-day only.
String output = zdt.format ( formatter );  // Generate a String to represent this date-time value.

Example, ready to run:

package javatimestuff;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Basil Bourque
 */
public class TellTimeConsole {

    public static void main ( String[] args ) {
        TellTimeConsole app = new TellTimeConsole ();
        app.doIt ();
    }

    private void doIt () {
        System.out.println ( "INFO - TellTimeConsole::doIt - Running." );
        BeeperControl bc = new BeeperControl ();
        bc.beepEveryMinute ();  // Ask that object to launch the background thread to tell time every minute.
        try {
            Thread.sleep ( TimeUnit.MINUTES.toMillis ( 5 ) ); // Run for five minutes and then shutdown this main thread and the background thread too.
            bc.halt ();  // Ask that object to stop the background thread.
        } catch ( InterruptedException ex ) { // This main thread is either being woken-from-sleep or stopped.
            System.out.println ( "INFO - TellTimeConsole::doIt - main thread of TellTimeConsole app interrupted." );
            bc.halt ();  // Ask that object to stop the background thread.
        }
    }

    class BeeperControl {

        private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool ( 1 );
        private final ZoneId zoneId = ZoneId.of ( "America/Montreal" );
        private final Locale locale = Locale.CANADA_FRENCH;
        //private final DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM ).withLocale ( this.locale );
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "hh:mm:ss a" , this.locale );

        public void beepEveryMinute () {
            // Define task to be performed.
            final Runnable beeper = new Runnable () {
                public void run () {
                    try {
                        ZonedDateTime zdt = ZonedDateTime.now ( zoneId );
                        System.out.println ( "Now: " + zdt.format ( formatter ) );
                    } catch ( Exception e ) {
                        // Always surround your task code with a try-catch, as any uncaught exception causes the scheduler to cease silently.
                        System.out.println ( "Exception unexpectedly reached 'run' method. " + e.getLocalizedMessage () );
                    }
                }
            };
            // Start performing that task every so often.
            System.out.println ( "INFO - BeeperControl::beepEveryMinute - Scheduling the executor service to run now. Runs indefinitely." );
            final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate ( beeper , 0 , 1 , TimeUnit.MINUTES ); // (Runnable command, long initialDelay, long period, TimeUnit unit)
        }

        public void halt () {
            System.out.println ( "INFO - BeeperControl::halt - shutting down the ScheduledExecutorService." );
            scheduler.shutdown ();  // Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
            // scheduler.shutdownNow(); // Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
        }
    }

}

See this code run live in IdeOne.com. Can only run briefly there, then hits a time limit imposed by IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top