本帖最后由 monghuan 于 2011-12-8 18:46 编辑
- import java.util.Calendar;
- class ClockTest implements Runnable
- {
- private Calendar calendar = Calendar.getInstance();
- private int year = calendar.get(Calendar.YEAR);
- private int month = calendar.get(Calendar.MONTH)+1;
- private int day = calendar.get(Calendar.DAY_OF_MONTH);
- private int hour = calendar.get(Calendar.HOUR_OF_DAY);
- private int minute = calendar.get(Calendar.MINUTE);
-
- private int count=0;
- private boolean flag = true;
-
- public void run()
- {
-
- while(true)
- {
- synchronized(this)
- {
- if(flag)
- {
- try
- {
-
- System.out.println(year+"-"+month+"-"+day+"-"+hour+"-"+minute+"-"+Thread.currentThread().getName());
- count++;
- Thread.sleep(1000);
- if(count==5)
- {
- flag=false;
- count=0;
- notify();
- wait();
- }
- }
- catch(Exception e)
- {
- System.out.println(e.toString());
- }
- }
- else
- {
- try
- {
- flag=true;
- System.out.println("整点时间为:"+year+"-"+month+"-"+day+"-"+hour+"-"+minute+"-"+Thread.currentThread().getName());
- System.out.println("整点时间为:"+year+"-"+month+"-"+day+"-"+hour+"-"+minute+"-"+Thread.currentThread().getName());
- notify();
- wait();
- }
- catch(Exception e)
- {
- System.out.println(e.toString());
- }
- }
- }
-
- }
- }
- }
- public class Main
- {
- public static void main(String [] args)
- {
- ClockTest ct = new ClockTest();
- Thread t1 = new Thread(ct);
- Thread t2 = new Thread(ct);
- t1.start();
- t2.start();
- }
- }
复制代码 输出结果如下:- D:\>javac Main.java
- D:\>java Main
- 2011-12-8-16-18-Thread-0
- 2011-12-8-16-18-Thread-0
- 2011-12-8-16-18-Thread-1 //??搞不懂为何出现线程1,求解惑?
- 2011-12-8-16-18-Thread-1
- 2011-12-8-16-18-Thread-1
- 整点时间为:2011-12-8-16-18-Thread-0
- 整点时间为:2011-12-8-16-18-Thread-0
- 2011-12-8-16-18-Thread-1
- 2011-12-8-16-18-Thread-1
- 2011-12-8-16-18-Thread-1
- 2011-12-8-16-18-Thread-1
- 2011-12-8-16-18-Thread-1
- 整点时间为:2011-12-8-16-18-Thread-0
- 整点时间为:2011-12-8-16-18-Thread-0
- ......
复制代码 |
|