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

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

问题描述

我一直在尝试解决一个涉及使用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?

实际问题:有两个线程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

推荐答案

您描述了Producer-Consumer模式.

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天全站免登陆