package 基础实战;
/*消费者与生产者的问题
* ·生产者负责生产数据,消费者负责取走数据
* ·生产者每生产完一组数据之后,消费者就要取走一组数据
* 解决数据错位问题(非同步操作所造成):
* */
class Info{ //信息初始化类
private String title;
private String content;
private boolean flag = true; //初始生产标记为True,代表可以生产
//使用同步设置方法 (生产过程)
public synchronized void set(String title, String content){
//重复进入到set()里面,不能够生产,需要等待,其他线程不可进入抢占资源
if(this.flag == false){ //代表以及有数据正在生产
try {
/*wait()方法需要使用下面的notify()唤醒线程*/
super.wait(); //其他线程需要等待
}catch (InterruptedException e){
e.printStackTrace();
}
}
this.title = title;
//等待1s种的生产时间
try{
/*sleep()可以设置休眠时间,时间一到自动唤醒*/
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
this.content = content;
this.flag = false; //修改生产标记,代表正在生产,其他线程不可进入
super.notify(); //唤醒其他等待线程
}
public synchronized void get(){
if(this.flag == true){ //可以生产
try{
super.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
/*一秒钟的生产时间*/
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(this.title+":"+this.content);
this.flag = true; //生产完成,可以生产
super.notify(); //唤醒其他等待的线程
}
}
class Producer implements Runnable{
private Info info; //引用Info类的线程对象
public Producer(Info info){
this.info = info;
}
/*与下面get()方法同步set(生产)数据*/
@Override
public void run() {
for (int x=0; x<100; x++){
if(x % 2!=0){
this.info.set(x+":"+"学生","A");
}else{
this.info.set(x+":"+"老师","B");
}
}
}
}
class Customer implements Runnable{
/*引用Info类里的线程对象*/
private Info info;
public Customer(Info info){
this.info = info;
}
@Override
public void run() {
for (int x = 0; x<100; x++) {
/*使用同步get()方法获取数据*/
this.info.get();
}
}
}
public class Demo_01 {
public static void main(String[] args){
Info info = new Info();
//使用Runnable接口实现多线程
new Thread(new Producer(info)).start();
new Thread(new Customer(info)).start();
}
}
Java中多线程的同步
猜你喜欢
转载自blog.csdn.net/qq_37504771/article/details/88763164
今日推荐
周排行