您的位置:首页 > 其它

004-线程同步问题引出、同步问题解决、死锁、生产者与消费者

2017-09-25 21:22 477 查看

一、同步问题引出

1、示例:

package com.lhx.thread.impl;

class Info {
private String title;
private String content;
private boolean flag = true;
// flag true 表示生产数据,但是不允许取走数据
// flag false 表示取走数据,但是不允许生产数据

public synchronized void set(String title, String content) {
if (flag == false) {
try {
super.wait();// 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title = title;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.content = content;
flag = false;
super.notify();
}

public synchronized void get() {
if (flag == true) {// 此时应该生产
try {
super.wait();// 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}

try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(title + "-->" + content);
flag = true;
super.notify();
}
}

class Productor implements Runnable {
private Info info = null;

public Productor(Info info) {
this.info = info;
}

@Override
public void run() {
for (int i = 0; i < 50; i++)
if (i % 2 == 0) {
this.info.set("张三", "衰哥");
} else {
this.info.set("李四", "帅哥");
}
}
}

class Consumer implements Runnable {
private Info info = null;

public Consumer(Info info) {
this.info = info;
}

public void run() {
for (int i = 0; i < 50; i++) {
info.get();
}
}
}

public class TestDemo2 {
public static void main(String[] args) throws Exception {
Info info = new Info();
Productor productor = new Productor(info);
Consumer consumer = new Consumer(info);
new Thread(productor).start();
new Thread(consumer).start();
}
}


View Code
解释一下sleep和wait区别
  sleep 是thread类定义的方法,在休眠到一定时间之后将自己唤醒
  wait是object类定义的方法,表示线程等待执行,必须通过notify()、notifyAll()来进行唤醒
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐