线程(死循环)执行后等待 使用计时器控制 5s后唤醒,重复执行
方法一
public class Test {
public static void main(String[] args) {
Lock lock=new Lock();
Runnable rb=new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (lock) {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date().getTime()));
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread th=new Thread(rb);
th.start();
Timer t=new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("唤醒");
synchronized (lock) {
lock.notify();
}
}
}, 3000,5000);
}
}
class Lock{
}
方法二,使用多线程
public class Test0_3 {
public static void main(String[] args) {
Lock11 lock=new Lock11();
Timer tt=new Timer();
tt.schedule(new TimerTask() {
@Override
public void run() {
synchronized (lock) {
lock.notifyAll();
}
}
}, new Date(), 1);
Th11 t1=new Th11(lock);
t1.start();
}
}
class Th11 extends Thread{
Lock11 lock;
public Th11(Lock11 lock2) {
super();
this.lock = lock2;
}
@Override
public void run() {
synchronized (lock) {
int i=0;
while(true){
try {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
lock.wait();
Thread.sleep(i+=5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
}
class Lock11{}