Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

java programming

Posted on 2004-10-04
13
Medium Priority
?
227 Views
Last Modified: 2010-03-31
public class FileSync {
  private File outFile;
  private PrintStream outStream;

  public FileSync() throws IOException {
      outFile = new File("c:/orisree/java/ran.txt");
      outStream = new PrintStream(new FileOutputStream(outFile));
  }

  public Object getSyncObject() {
      return outFile;
  }

  public void writeToFile(String text) throws IOException {
      outStream.println(text);
  }
}
**************************************************
public class TestSynch extends Thread {

  public TestSynch() {
  }
  public static void main(String[] args) {
      WriteThread[] threads = new WriteThread[3];
      try {
          for(int i = 0; i < threads.length; i++) {
              threads[i] = new WriteThread();
          }

          for(int i = 0; i < threads.length; i++) {
              threads[i].start();
          }

      }catch(IOException ioe) {
          ioe.printStackTrace(System.err);
      }
  }
}
***************************
public class WriteThread extends Thread {
  private static int threadCount;
  private int threadNum;
  private FileSync fileSync;

  static {
      threadCount = 0;
  }

  public WriteThread() throws IOException {
      threadNum = ++threadCount;
      fileSync = new FileSync();
  }

  public void run() {
      Object syncObject = fileSync.getSyncObject();
      synchronized(syncObject) {
          for(int i = 0; i < 100; i++) {
              try {
                  fileSync.writeToFile("Printing from thread " + threadNum + " line " + i);
              }catch(IOException ioe) {
                  ioe.printStackTrace(System.err);
              }
          }
      }
  }
}



From the above 3 classes,when i run TestSynch i get output , for 1 to 21, i get threadnum=1
then from 22 to 54, i get threadnum=3 ,after that until 99 i get threadnum=1,
How does synchObject allow thread 3 to come in between thread 1.pls give me the answer at the earliest.
Urgent..


0
Comment
Question by:sraveend
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 2
  • 2
  • +2
13 Comments
 
LVL 92

Expert Comment

by:objects
ID: 12221503
>       synchronized(syncObject) {

the synchronized code block can only be run by one thread at a time.
other will be blocked until the thread completes the block.
0
 
LVL 92

Assisted Solution

by:objects
objects earned 600 total points
ID: 12221521
0
 

Author Comment

by:sraveend
ID: 12221680
U r correct only one thread runs,then how i got the thread 3 in between thread1 in my program
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 92

Expert Comment

by:objects
ID: 12221707
thats just how the threads get scheduled, try running it a few times and see.
0
 
LVL 92

Expert Comment

by:objects
ID: 12221771
0
 
LVL 4

Expert Comment

by:aratani
ID: 12222382
Basically, every thread takes some time on the CPU. Then, after its time is taken the next thread gets its chance. So, from 1-21 was threads 1 time running on the CPU. Then, you got thread 3  to run on the CPU. And so on, the scheduling is fully random.

Is that what you are looking for, or do you want to know how to block Thread 1 to execute?

AJ
0
 
LVL 92

Expert Comment

by:objects
ID: 12222417
> And so on, the scheduling is fully random.

not sure that its exactly random
0
 
LVL 2

Expert Comment

by:gen718
ID: 12223339
It's not random. Higher priority threads get more processor time than lower priority threads. Other than that, the exact behavior (thread selection) is dependent on the VM and the operating system.

A running thread remains running until it blocks, yields or is forcibly swapped off the processor by the thread scheduler.
0
 
LVL 92

Expert Comment

by:objects
ID: 12223393
yes that sounds better, the link above provides some more details.
0
 

Author Comment

by:sraveend
ID: 12227044
I just don't find any difference in the output with Synchronization code or without synchronization code.
Is it due to ,blocking only the file and not the printstream object.I just want to know the role of synchronization......
0
 
LVL 4

Accepted Solution

by:
aratani earned 900 total points
ID: 12229389
The role of synchronization is to protect data from being accessed when it shouldn't be. For example, if you have two threads accessing the same data then you might not want both the threads to change the data at the same time. So, you would synchronize the method or the section of the code that changes the data to prevent it from being accessed simultaneously.

http://www.janeg.ca/scjp/threads/synchronized.html

will show you the purpose behind synchronized.

In your code,

saying synchronized (syncObject) {


}

gets a lock on the syncObject at the start of the code. So, now no other threads can modify or work with syncObject. And it is released at the end of the closing brace (}).

To find out more about using the synchronized keyword, read this,

http://www.jguru.com/faq/view.jsp?EID=42569

Also, raed about the article on what it means to get a lock?

The reason there is no difference in the synchronized code and non-synchronized is since they are not changing the object in any way. If you look at the first link I showed you, you will see the purpose of synchronization.

AJ
0
 
LVL 92

Expert Comment

by:objects
ID: 12232161
> .I just want to know the role of synchronization......

It is to ensure only one threads executes a block of code at the same time.
0
 
LVL 15

Expert Comment

by:babuno5
ID: 12238716
Hello,
I think this might just help u
try setting the Priority of the threads set the maximum priority which is to be completed first

Thread.MAX_PRIORITY
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question