• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the code below, I have a class LearnNumbers that is using an object of another class.
I would like to synchronize LearnNumbers using the keyword synchronized such that only one thread can execute the methods at a point of time and the entire method learn is not synchronized together. Rather, only the lines of code where num is being accessed, should be synchronized.How ould I achieve this?

class LearnNumbers
{
Numbers num = new Numbers();
public void learn()
{
if(num == 1)
num.printOne();
else if(num == 2)
num.printTwo();
else
num.printThree();
}
}
class Numbers
{
public void printOne()
{
System.out.println("You are printing One");
}
public void printTwo()
{
System.out.println("You are printing Two");
}

public void printThree()
{
System.out.println("You are printing Three");
}
}
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This will not work at all.
You test for (num == 1) so num seems to be an int.
On the other side you declare 'Numbers num'.
In allmost every case a class should be named in singular form, if you build several instances of it. An exception from that rule could be a collection:

Why do you want to synchronize?
You may synchronize a single statement:

but I guess it's a bit early to deal with synchronization...
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic