日期:2014-05-20 浏览次数:21131 次
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeGain implements Runnable {
Date nDate = null ;
public void run() {
int i = 0;
while (i < 24) {
i++;
System.out.println(i);// 此处处理逻辑
// try {
// //获取时间
// SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
// Date date = new Date();
// date.setHours(0);
// date.setMinutes(0);
// Hashtable<String,Date> temp = new Hashtable<String,Date>();
//
//
// System.out.println(sdf.format(date));
// if(date.getHours()<12){
// System.out.println(sdf.format(date)+"am");
// }else{
// System.out.println(sdf.format(date)+"pm");
// }
// Thread.sleep(60000);
// } catch (Exception e) {
// e.printStackTrace();
// }
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
Date initDate = getInitDate();
initDate.setMinutes(initDate.getMinutes()+1);
if(initDate.getHours()<12){
System.out.println(sdf.format(initDate)+"am");
}else{
System.out.println(sdf.format(initDate)+"pm");
}
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public Date getInitDate(){
if(nDate == null){
nDate = new Date();
nDate.setHours(0);
nDate.setMinutes(0);
}
return nDate;
}
public static void main(String[] args) {
TimeGain tt = new TimeGain();
Thread t = new Thread(tt);
t.start();
}
}
public class TimeGain implements Runnable {
public void run() {
int hh = 0;
int mm = 0;
while (hh < 24) {
try {
System.out.printf("\"%02d:%02d%s\",", hh, mm, (hh < 12 ? "am" : "pm"));
mm++;
if (mm == 60) {
mm = 0;
hh++;
}
if (hh == 24) {break;}
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TimeGain tt = new TimeGain();
Thread t = new Thread(tt);
t.start();
}
}
------解决方案--------------------
我的建议用定时器做也可以
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int h = 0;
static int m = 0;
public static void main(String[] args) throws Exception {
TimerTask task = new TimerTask() {
@Override
public void run() {
// 调用业务方法
System.out.printf("\"%02d:%02d%s\",", h, m, (h < 12 ? "am"
: "pm"));//复制阿宝的,嘿嘿,学习了!
m++;
if (m == 60) {
m = 0;
h++;
}
if (h == 12)
h = 0;
}
};
// 创建一个定时器
Timer timer = new Timer();
// 设值 3 秒钟后开始执行第一次,以后每隔 1 秒中执行一次
// timer.schedule(task, 3 * 1000, 1 * 1000);
// 设值现在开始执行第一次,以后每隔 60 秒中执行一次
timer.schedule(task, new Date(), 60 * 1000);
}
}