开发者学堂课程【Java 高级编程:利用 Object 类解决重复操作】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/20/detail/295
利用 Object 类解决重复操作
一.线程等待与唤醒
如果说现在要想解决生产者与消费者的问题,那么最好的解决方案就是使用等待与.唤醒机制,而对于等待与唤醒的操作机制,主要依靠的是 Object 类中提供的方法处理的:
l 等待: public final void wait() throws InterruptedException; .
死等: public final void wait() throws InterruptedException; .
设置等待时间: public final void wait(long timeout) throws InterruptedExcej|
设置等待时间: public final void wait(long timeout, int nanos) throws Interru
l 唤醒第一个等待线程: public final void notify();.·
l 唤醒全部等待线程: public final void notifyAll():
如果此时有若干个等待线程的话,那么 notify() 表示的是唤醒第一个等待的,而其它的线程继续等待.而 notify All()表示醒所有等待的线程,哪个线程的优先级高就有可能先执行。
对于当前的问题主要的解决应该通过 Message 类完成处理。
范例:修改 Message 类:
Package cn.mldn.demo;
class Message{
private String title;
private String content;
private boolean flag;//表示生产或消费的形式
//flag=true:允许生产,但是不允许消费
//flag=false:允许消费,不允许生产
public synchronized void set(String title,String content) {
if (!this.flag) { // 无法进行生产,应该等待被消费
try {
super.wait();
} catch (InterruptedException e){
e.printStackTrace();
this.title=title ;
try{
Thread.sLeep(100);
}catch (InterruptedException e) {
e.printStackTrace();
this.content=content;
public synchronized String get() {
public synchronized String get() {
if (this.flag == true) { // 还未生产,需要等待
try {
super.wait();
}catch (InterruptedException e) {
e.printStackTrace();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
try {
return this.title + - + this.content;
} finally { //不管如何都要执行
this.flag = true ; //继续生产
super.notify(); //唤醒等待线程
public class ThreadDemo {
public static void main(String[]args) throws Exception {
注:这种处理形式就是在进行多线程开发过程之中最原始的处理方案,整个的等待、同步唤醒机制都有开发者自行通过原生代码实现控制。