多线程之间实现通讯(生产者与消费者)

多线程之间通讯实现(并解决线程安全问题)

class Res {
    public String userName;
    public String sex;
}

class InputThread extends Thread {
    private Res res;

    public InputThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
             synchronized (res) {
            if (count == 0) {
                res.userName = "余胜军";
                res.sex = "男";
            } else {
                res.userName = "小红";
                res.sex = "女";
            }
            count = (count   1) % 2;
        }

        }
    }
}

class OutThrad extends Thread {
    private Res res;

    public OutThrad(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                System.out.println(res.userName   ","   res.sex);
            }
        }

    }
}

public class ThreadDemo01 {

    public static void main(String[] args) {
        Res res = new Res();
        InputThread inputThread = new InputThread(res);
        OutThrad outThrad = new OutThrad(res);
        inputThread.start();
        outThrad.start();
    }

}

这种方式的问题在于,会进行多次消费

wait、notify方法

多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同。

  1. 因为涉及到对象锁,他们必须都放在synchronized中来使用. Wait、Notify一定要在synchronized里面进行使用。
  2. Wait必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行
  3. notify/notifyall: 唤醒因锁池中的线程,使之运行

注意:一定要在线程同步中使用,并且是同一个锁的资源

class Res {
    public String userSex;
    public String userName;
    //线程通讯标识
    public boolean flag = false;
}
class IntThrad extends Thread {
    private Res res;

    public IntThrad(Res res) {
        this.res = res;        
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                       // 当前线程变为等待,但是可以释放锁
                        res.wait();
                    } catch (Exception e) {

                    }
                }
                if (count == 0) {
                    res.userName = "小军";
                    res.userSex = "男";
                } else {
                    res.userName = "小紅";
                    res.userSex = "女";
                }
                count = (count   1) % 2;
                res.flag = true;
                // 唤醒当前线程
                res.notify();
            }

        }
    }
}
class OutThread extends Thread {
    private Res res;

    public OutThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (!res.flag) {
                    try {
                        res.wait();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                System.out.println(res.userName   "--"   res.userSex);
                res.flag = false;
                res.notify();
            }
        }
    }
}

public class ThreaCommun {
    public static void main(String[] args) {
        Res res = new Res();
        IntThrad intThrad = new IntThrad(res);
        OutThread outThread = new OutThread(res);
        intThrad.start();
        outThread.start();
    }
}

wait与sleep区别

对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。

sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

在调用sleep()方法的过程中,线程不会释放对象锁。

而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备

获取对象锁进入运行状态。

Lock锁

在 jdk1.5 之后,并发包中新增了 Lock 接口(以及相关实现类)用来实现锁功能,Lock 接口提供了与 synchronized 关键字类似的同步功能,但需要在使用时手动获取锁和释放锁。

Lock写法

Lock lock  = new ReentrantLock();
lock.lock();
try{
//可能会出现线程安全的操作
}finally{
//一定在finally中释放锁
//也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
  lock.ublock();
}

Lock与synchronized 关键字的区别

  • Lock 接口可以尝试非阻塞地获取锁 当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁。
  • Lock 接口能被中断地获取锁 与 synchronized 不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放。
  • Lock 接口在指定的截止时间之前获取锁,如果截止时间到了依旧无法获取锁,则返回。

Condition用法

Condition的功能类似于在传统的线程技术中的,Object.wait()和Object.notify()的功能。代码

Condition condition = lock.newCondition();
res. condition.await();  类似wait
res. Condition. Signal() 类似notify
class Res {
    public String userName;
    public String sex;
    public boolean flag = false;
    Lock lock = new ReentrantLock();
}

class InputThread extends Thread {
    private Res res;
    Condition newCondition;
    public InputThread(Res res,    Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            // synchronized (res) {

            try {
                res.lock.lock();
                if (res.flag) {
                    try {
//                        res.wait();
                        newCondition.await();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                if (count == 0) {
                    res.userName = "小军";
                    res.sex = "男";
                } else {
                    res.userName = "小红";
                    res.sex = "女";
                }
                count = (count   1) % 2;
                res.flag = true;
//                res.notify();
                newCondition.signal();
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                res.lock.unlock();
            }
        }

        // }
    }
}

class OutThrad extends Thread {
    private Res res;
    private Condition newCondition;
    public OutThrad(Res res,Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        while (true) {
//            synchronized (res) {
            try {
                res.lock.lock();
                if (!res.flag) {
                    try {
//                        res.wait();
                        newCondition.await();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                System.out.println(res.userName   ","   res.sex);
                res.flag = false;
//                res.notify();
                newCondition.signal();
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                res.lock.unlock();
            }
//            }
        }

    }
}

public class ThreadDemo01 {

    public static void main(String[] args) {
        Res res = new Res();
        Condition newCondition = res.lock.newCondition();
        InputThread inputThread = new InputThread(res,newCondition);
        OutThrad outThrad = new OutThrad(res,newCondition);
        inputThread.start();
        outThrad.start();
    }

}

测试一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个使用C实现多线程通信示例: ``` #include <stdio.h> #include <pthread.h> #define BUFFER_SIZE 10 int buffer[BUFFER_SIZE]; int count = 0; // 缓冲区中元素个数 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁 pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER; // 初始化条件变量(生产者) pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER; // 初始化条件变量(消费者) void *producer(void *arg) { int i; for (i = 0; i < 20; i++) { pthread_mutex_lock(&mutex); // 加锁 while (count == BUFFER_SIZE) { // 缓冲区满了,等待消费者消费 pthread_cond_wait(&cond_producer, &mutex); } buffer[count++] = i; // 生产一个元素 printf("生产者线程 %ld 生产了 %d\n", pthread_self(), i); pthread_cond_signal(&cond_consumer); // 通知消费者消费 pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } void *consumer(void *arg) { int i, data; for (i = 0; i < 20; i++) { pthread_mutex_lock(&mutex); // 加锁 while (count == 0) { // 缓冲区空了,等待生产者生产 pthread_cond_wait(&cond_consumer, &mutex); } data = buffer[--count]; // 消费一个元素 printf("消费者线程 %ld 消费了 %d\n", pthread_self(), data); pthread_cond_signal(&cond_producer); // 通知生产者生产 pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, producer, NULL); pthread_create(&tid2, NULL, consumer, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; } ``` 在这个示例中,有两个线程:生产者消费者。它们共享一个缓冲区,生产者将元素放入缓冲区中,而消费者从缓冲区中取出元素。当缓冲区满了,生产者就会等待消费者消费;当缓冲区空了,消费者就会等待生产者生产。这个示例使用了互斥锁和条件变量来实现线程间的同步和互斥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛!Destiny

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值