• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads accessing a program  RSS feed

 
Ranch Hand
Posts: 415
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have a question which needs some expert advise . I have a class which looks like this

class A
{

public int i = 0;

public int read()
{
return i;
}

public void write()
{
i++;
}
}

This program needs to be modified in a such a way that

1. Two threads should be able to read the value of i
2. Two threads should not be able to write at a time
3. Read should not be allowed when write is happening because of some thread

Can any one let me know the best way of doing this ??
 
author
Sheriff
Posts: 23513
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is hardly an advanced topic. In fact, it seems more like a homework questions. Anyway, the Sun tutorial on synchronization should be a good point for you to start.

Henry
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I am no expert by if you are using JDK 1.5 there is an easy way of doing that.

Take a look at the ReentranteadWriteLock class and the ReadWriteLock interface.

Using the methods there you can easily implement your criteria.
 
author and iconoclast
Sheriff
Posts: 24219
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to "Threads and Synchronization."
 
Bring out your dead! Or a tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!