forked from rick2785/JavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetTime20.java
More file actions
67 lines (51 loc) · 1.94 KB
/
GetTime20.java
File metadata and controls
67 lines (51 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// By using threads you can execute multiple blocks
// of code at the same time. This program will output
// the current time and then at a specific time execute
// other code without stopping the time output
// Need this for Date and Locale classes
import java.util.*;
// Need this to format the dates
import java.text.DateFormat;
// By extending the Thread class you can run your code
// concurrently with other threads
public class GetTime20 extends Thread{
// All of the code that the thread executes must be
// in the run method, or be in a method called for
// from inside of the run method
public void run(){
// Creating fields that will contain date info
Date rightNow;
Locale currentLocale;
DateFormat timeFormatter;
DateFormat dateFormatter;
String timeOutput;
String dateOutput;
// Output the current date and time 20 times
for(int i = 1; i <= 20; i++){
// A Date object contains date and time data
rightNow = new Date();
// Locale defines time formats depending on location
currentLocale = new Locale("en", "US");
// DateFormat allows you to define dates / times using predefined
// styles DEFAULT, SHORT, MEDIUM, LONG, or FULL
// getTimeInstance only outputs time information
timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
// getDateInstance only outputs time information
dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale);
// Convert the time and date into Strings
timeOutput = timeFormatter.format(rightNow);
dateOutput = dateFormatter.format(rightNow);
System.out.println(timeOutput);
System.out.println(dateOutput);
System.out.println();
// You must wrap the sleep method in error handling
// code to catch the InterruptedException exception
// sleep pauses thread execution for 2 seconds below
try {
Thread.sleep(2000);
}
catch(InterruptedException e)
{}
}
}
}