多线程-线程安排-休眠与唤醒
package com.liujinghe.lianxi1.a_thread;
import java.util.Set;
class Message{
//创建一个类,这个类的对象当成一个锁对象来看待
private String message;
public Message() {
// TODO Auto-generated constructor stub
}
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Waiter implements Runnable{
//创建一个类,写休眠方法
private Message message;
public Waiter(Message message) {
// TODO Auto-generated constructor stub
this.message = message;
}
@Override
public void run() {
// TODO Auto-generated method stub
//获取当前线程的名字
String name = Thread.currentThread().getName();
System.out.println(name+"是休眠线程");
//加锁
synchronized(message) {//message这个对象只有一个线程能操作
System.out.println(name + "开始等待的时间:"+System.currentTimeMillis());
try {
message.wait();//线程开始休眠
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//没有notify方法,下面的代码不会被执行
System.out.println(name+"别唤醒的时间:"+System.currentTimeMillis());
System.out.println(name+"线程"+message.getMessage());
}
}
}
class Notifier implements Runnable{
//创建一个类,写唤醒方法
private Message message;
public Notifier(Message message) {
// TODO Auto-generated constructor stub
this.message = message;
}
@Override
public void run() {
// TODO Auto-generated method stub
//获取当前线程的名字
String name = Thread.currentThread().getName();
System.out.println(name+"是唤醒线程");
//让唤醒的线程在休眠后的线程执行后再执行
try {
Thread.sleep(3000);
//对message加锁
synchronized(message) {
message.setMessage("呵呵哒,醒来");
//随机唤醒一个线程
//message.notify();
//唤醒全部线程
message.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Demo4 {
public static void main(String[] args) {
//线程的休眠与唤醒
//创建类对象
Message message = new Message("我是message");
//创建休眠线程
Waiter waiter1 = new Waiter(message);
Waiter waiter2 = new Waiter(message);
new Thread(waiter1,"休眠线程1").start();
new Thread(waiter2,"休眠线程2").start();
//创建唤醒线程
Notifier notifier = new Notifier(message);
new Thread(notifier,"唤醒线程").start();
}
}
运行截图