- package base;
-
- public class State implements Runnable {
- //当前线程等待1秒或其他线程调用notify或notifyAll()方法
- public synchronized void waitFirst() throws InterruptedException {
- wait(1000);
- System.out.println("我爱你");
-
- }
- //当前线程等待永久秒或其他线程调用notify或notifyAll()方法
- public synchronized void waitSecond() throws InterruptedException {
- wait();
- System.out.println(
- "I hate you");
- }
- //唤醒有调用wait() third方法进入等待状态的线程
- public synchronized void notifyNow() throws InterruptedException {
- notify();
-
- }
-
-
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- try {
- waitFirst();
- waitSecond();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
-
-
- }
-
-
-
- package base;
-
- public class Test {
-
- public static void main(String[] args) throws InterruptedException {
- State state=new State();
- Thread thread =new Thread(state);
- //输出线程状态
- System.out.println("新建"+thread.getState());
- thread.start();
- System.out.println("启动"+thread.getState());
- thread.sleep(200);//使新线程waitFirst()方法
- System.out.println("计时"+thread.getState());
- thread.sleep(2000);//使新线程waitSecond()方法
- System.out.println("唤醒 "+thread.getState());
- state.notifyNow();
- System.out.println("等待"+thread.getState());
- thread.sleep(4000);//当前线程休眠4秒,使新线程
- System.out.println("终止"+thread.getState());
-
-
-
- }
- }