题目: 1.开始所经历时间的程序,每5秒打印一条消息。 2.消息打印线程由事件打印线程通知,在不改变时间线程打印线程的前提下,增加一个每隔7秒打印另一条消息的线程
代码:
public class Controller extends Thread{ private Date date ;//对象锁 private boolean flag = false;//控制唤醒或等待线程 public Controller(Date date){ this.date = date; } @Override public void run() { while(true){ synchronized(date){ if(flag){ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } date.notify(); flag = false; } } } } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } class PrintMessage extends Thread{ @Override public void run() { while(true){ synchronized(date){ if(!flag){ try { flag = true; date.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("5秒的消息"); } } } } public static void main(String[] args) { Date date = new Date(); //打印5秒消息的线程 Controller controller = new Controller(date); PrintMessage printMessage = controller.new PrintMessage(); printMessage.start(); controller.start(); //不影响打印线程的7秒消息线程 new Thread(new Runnable(){ @Override public void run() { while(true){ try { Thread.sleep(7000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("7秒的消息"); } } }).start(); } }