线程同步 - 如何交替执行线程 [英] Thread Synchronization - How to execute threads alternatively

查看:30
本文介绍了线程同步 - 如何交替执行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 wait() 和 notify() 解决涉及线程通信的问题.基本上我有 2 个线程 T1 和 T2,我希望它们按以下顺序执行

I have been trying to solve a problem involving thread communication using wait() and notify(). Basically i have 2 threads T1 and T2 and i want them to be executed in the following order

T1,T2,T1,T2 .....我怎样才能做到这一点?

T1 , T2, T1, T2 ..... How can i achieve that?

实际问题:有 2 个线程 T1 - 打印奇数(比如 1 - 100)和 T2 - 打印偶数(1 - 100).现在,输出应该是 1, 2, 3, 4 , 5 , .... 100

Actual Problem: There are 2 threads T1 - which prints odd numbers (say 1 - 100) and T2 - which prints even numbers (1 - 100). Now, the output should be 1, 2, 3, 4 , 5 , .... 100

推荐答案

你描述了一个生产者-消费者模式.

You describe a Producer-Consumer pattern.

它是许多 Java 书籍中描述的 Java 实现,包括 M.Grand Java 中的模式.第一卷"和 Naughton 和 Schildt 的Java 2:完整参考".

It's java implementations described in numerous java books including M.Grand "Patterns in Java. Volume I" and "Java 2: The Complete Reference" by Naughton and Schildt.

基本思想:两个线程都应该使用 1 个监视器(即它们的代码应该在 synchronized(monitor) {} 块内).您还需要一些标志变量,它应该指示两个线程中的哪一个当前应该工作.

Basic idea: both threads should use 1 monitor (i.e. their code should be inside synchronized(monitor) {} blocks). You also need some flag variable which should indicate which of two threads should work at the moment.

当你的一个线程在同步块内时,它应该检查标志变量是否轮到他来做这项工作.如果是,让它工作,然后更改标志值,然后通知所有等待线程.如果没有,那么它应该等待.

When one of your threads is inside synchronized block it should check flag variable whether it's his turn to do the job. If yes, let it work and then change flag value and then notify all waiting threads. If no, then it should wait.

这篇关于线程同步 - 如何交替执行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆