473,403 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Threading and shared array

hi! whew! been a while since i last posted. anyway, I have this code, but I'm trying to figure out a way to access a shared variable within the threads.

here's the main program:
Expand|Select|Wrap|Line Numbers
  1. public class FeedFrenzy{
  2.     public static void main(String args[]){
  3.         Frenzy frenzy = new Frenzy();
  4.         Fish fish1 = new Predator();
  5.         Prey minnow = new Prey();
  6.         frenzy.setName("Frenzy");
  7.         minnow.setName("Golden Minnow");
  8.         fish1.setName("Small Fishy");
  9.         Monitor mon;   //this is what I want to access in each thread
  10.               (new Thread(fish1)).start();
  11.         (new Thread(frenzy)).start();
  12.         (new Thread(minnow)).start();
  13.     }
  14. }
  15.  
this is a simple monitor. what it does is just keep a 2d array of the location of the fish, much like a cartesian plane.

Expand|Select|Wrap|Line Numbers
  1. public class Monitor {
  2.     Fish fishGrid[][] = new Fish[100][100];
  3.     public Fish check (int loc_x, int loc_y){
  4.         return fishGrid[loc_x][loc_y];
  5.     }
  6.     public void move(Fish fish, int loc_x, int loc_y){
  7.         //do something
  8.     }
  9. }
  10.  

this is where I want to access mon:
Expand|Select|Wrap|Line Numbers
  1. public class Fish implements Runnable {
  2.     ...
  3.     public void run(){
  4.         int direction = 0;
  5.         if (!(life > 0)) alive = false;  //checks each time if fish is alive
  6.         while (alive) {
  7.             /* access mon here and update the grid
  8.                     something like:
  9.                      mon.fishGrid[location_x][location_y] = this;
  10.                 */
  11.             direction = (int)(Math.random() * 4 ) + 1;
  12.             swim(direction);
  13.             try {
  14.                 Thread.sleep(1000);
  15.             }catch (Exception e){
  16.                 System.out.println("cannot set delay");
  17.             }
  18.         }
  19.     }
  20. }
  21.  
well, i guess that's it. I hope someone could help. Thanks so much guys!
Jun 13 '09 #1
7 3006
JosAH
11,448 Expert 8TB
Pass your monitor around to every thread that has to deal with it so they know where to find it. The code in the monitor object that is stamped to be critical should synchronize on the monitor object itself. That's all there is to it ...

kind regards,

Jos
Jun 13 '09 #2
that's exactply what i thought i wanted to do, but the question is how? err, could you spare some coded examples?

thanks for the reply Jos.. :D
Jun 13 '09 #3
JosAH
11,448 Expert 8TB
Something like this:

Expand|Select|Wrap|Line Numbers
  1. Monitor monitor= new Monitor(); 
  2. Frenzy frenzy= new Frenz(monitor); // pass the monitor
  3. Fish fish= new Fish(monitor); // pass it again
  4. ...
  5. public class Frenzy {
  6.    private Monitor monitor; // points to a monitor;
  7.    public Frenzy(Monitor monitor) { this.monitor= monitor; }
  8.    ...
  9.    public Fish peek(int x, int y) {
  10.       return monitor.peek(x, y); // consult the monitor
  11.    }
  12.    ...
  13. }
  14. ...
  15. public class Monitor {
  16.    private Fish[][] fish= new Fish[10][10]; // or whatever
  17.    ...
  18.    public synchronized Fish peek(int x, int y) {
  19.       return fish[x][y]; // no other thread can access this matrix
  20.    }
  21.    public synchronized  void poke(Fish aFish, int x, int y) {
  22.       fish[x][y]= aFish; // no other thread can access this matrix
  23.    }
  24. }
  25.  
I hope you get the picture,

kind regards,

Jos
Jun 13 '09 #4
whoa! so that's how!:D I get it now. really appreaciate it.

Just a quick question:
so when the monitor is passed, all i have to do is create a constructor for it, and i don't have to modify the part where i wrote this
Expand|Select|Wrap|Line Numbers
  1. (new Thread(fish1)).start();
  2. (new Thread(frenzy)).start();
  3. (new Thread(minnow)).start();
  4.  
?

Thanks again Jos

Kazuo
Jun 13 '09 #5
JosAH
11,448 Expert 8TB
@jrhitokiri
Yep, simply pass that monitor to your other objects (a constructor is a fine place for that but a 'setMonitor(...)' method would be fine too if you don't forget to call it (that's why a ctor is better). The monitor itself should take care of its critical sections (synchronize) while the other classes in their own threads know nothing.

kind regards,

Jos
Jun 13 '09 #6
got it.:D

thanks again!:D this was quite helpful.

KaZuo
Jun 13 '09 #7
JosAH
11,448 Expert 8TB
@jrhitokiri
You're welcome of course.

kind regards,

Jos
Jun 13 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

17
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next...
0
by: James R. Saker Jr. | last post by:
I've got a: "start server thread > Queue object, start server thread <> Queue object, start parsing client < Queue object" application that's got me puzzled. Probably an easy threads issue, but...
37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours,...
6
by: CJ Taylor | last post by:
Hey Everyone, Alright, now I cannot get this to work, I may be dumb and don't see it, but sickness will do that every now and then. So I have a program with 4 threads performing unique...
0
by: Pawan Narula via DotNetMonster.com | last post by:
hi all, i'm using VB.NET and trying to code for contact management in a tree. all my contacts r saved in a text file and my C dll reads them one by one and sends to VB callback in a sync mode...
13
by: Bob | last post by:
My WinForms app runs on the single default thread, and uses a single SqlConnection object for all queries. I need to use one or more timers to periodically execute some of them. My own testing...
0
by: Colmeister | last post by:
I recently read Jason Clark's excellent article on Unhandled Exceptions (http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx) and have attempted to incorporate the features he talks...
14
by: Simon Verona | last post by:
I think I'm doing this wrong : I have a class with a public shared method such as follows: public shared sub myFunction dim frm as new myFrm dim t as new Threading.Thread(Addressof ...
126
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard:...
3
by: Bill Schanks | last post by:
I have a form that gets opened, and it a separate thread I want a timer at the bottom of the form to update while the datagridview is updating. In my main form I have this: Dim t As New...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.