Thread Programming

Can anybody answer me the foolwing questions?
1. How do I use the methods notify, notifyAll() in class Object?
Are they used to wake up the threads who are waiting on the object?
2. What means the keyword synchronized?
I heard about a lock on a object. Can you explain me, please.
3. There is also the possibility to use synchronized with methods.
Where is the difference?
4. How can I use the methods interrupted() and isInterrupted() in the Thread class?
What do they do?
Thanks in advance
Djamal

Can anybody answer me the foolwing questions?
1. How do I use the methods notify, notifyAll() in
class Object?notifyAll() will wake up all threads "waiting" for the objects lock you called it on. notify() will only wake up one (it's random)
Are they used to wake up the threads who are
re waiting on the object?
2. What means the keyword synchronized?synchronized is used to prevent concurrent access to a block of code (only one thread at a time) When you enter a synchronized block you aquire the lock for an object. A thread must aquire the lock before entering the block. Hence.. one thread at a time
I heard about a lock on a object. Can you explain
ain me, please.
3. There is also the possibility to use synchronized
with methods.methods can be synchronized, as can smaller code blocks.
Where is the difference?no difference only convinence
4. How can I use the methods interrupted() and
isInterrupted() in the Thread class?
What do they do?interrupt() attempts to interrupt the thread it is called on. It it used in a multitude of ways.
Thanks in advance
Djamalalso.. "The" book on Threads in java
http://java.sun.com/docs/books/cp/
And Doug Lea's site
http://gee.cs.oswego.edu/
You need to understand the design before you can code this stuff correcty. Also JSR 166 will be basically Doug Lea's concurrent package as java.util.concurrent.

Similar Messages

  • Running a Java Multi Thread Program in database

    I have created a multi threaded program in Java and it runs successfully from the command prompt. I want to create a DBMS Job which will wake up at regular intervals and runs the java program(Java stored procedure). Is this possible in 9.2/10G ?? If Yes, will there be any impact on the DB performance/increase memory etc.,
    The database (9.2...) resides on a RH 2.3 AS box.
    Any ideas...
    Thanks,
    Purush

    Purush,
    Java stored procedures cannot be multi-threaded. Well, they can, but the threads will not run in parallel. You may be able to find some more information in the Oracle documentation, which is available from:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • Thread programming -  variable might not have been initialized

    Hi there,
    Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
    ThreadController.java:42: variable dataGeneratorThread might not have been initialized
    dataGeneratorThread.activeCount();
    The bit I dont understand is that I run
    this line here
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    but when I do
    dataGeneratorThread.activeCount()
    is balks.
    I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
    Here is some of the code
    runable class{
    new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
    public class ThreadController implements Runnable {
    DataBuffer inputBuffer;
    DataBuffer displayBuffer;
    JuliaCalc juliaCalc;
    /** Creates a new instance of ThreadController */
    public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
    inputBuffer = inputBuffer;
    displayBuffer = displayBuffer;
    juliaCalc = juliaCalc;
    public void run()
    DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
         WorkerThread dataGeneratorThread;
         for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators[i],juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    dataGeneratorThread.activeCount();
    int nNanoSecsBeforeCheck = 50;
    while(true)
    if(dataGeneratorThread.isAlive()){
    if(dataGeneratorThread.activeCount() > inputBuffer.size())
    public class DataGenerator implements Runnable {
    int nImageWidth;
    int nImageHeight;
    DataBuffer inputBuffer;
    public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
    nImageWidth = ImageWidth;
    nImageHeight = ImageHeight;
    public void run()
    // Non terminating thread - created datapakets and place them in the input buffer
    // Get two radom number withoin a bound and find out bout default highest colou - 3rd value
    while(true)
    int nRandomXCord;
    int nRandomYCord;
    nRandomXCord = ((int)(Math.random() * nImageWidth));
    nRandomYCord = ((int)(Math.random() * nImageHeight));
    DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
    inputBuffer.put(dpDataPacket);

    Sorry about that, didnt realise.
    Hi there,
    Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
    ThreadController.java:42: variable dataGeneratorThread might not have been initialized
    The bit I dont understand is that I run
    this line here
    this line here
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    }but when I do
    dataGeneratorThread.activeCount() is balks.
    I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
    Here is some of the code
    runable class{
    new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
    public class ThreadController implements Runnable {
    DataBuffer inputBuffer;
    DataBuffer displayBuffer;
    JuliaCalc juliaCalc;
    /** Creates a new instance of ThreadController */
    public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
    inputBuffer = inputBuffer;
    displayBuffer = displayBuffer;
    juliaCalc = juliaCalc;
    public void run()
    DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
    WorkerThread dataGeneratorThread;
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    dataGeneratorThread.activeCount();
    int nNanoSecsBeforeCheck = 50;
    while(true)
    if(dataGeneratorThread.isAlive()){
    if(dataGeneratorThread.activeCount() > inputBuffer.size())
    public class DataGenerator implements Runnable {
    int nImageWidth;
    int nImageHeight;
    DataBuffer inputBuffer;
    public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
    nImageWidth = ImageWidth;
    nImageHeight = ImageHeight;
    public void run()
    // Non terminating thread - created datapakets and place them in the input buffer
    // Get two radom number withoin a bound and find out bout default highest colou - 3rd value
    while(true)
    int nRandomXCord;
    int nRandomYCord;
    nRandomXCord = ((int)(Math.random() * nImageWidth));
    nRandomYCord = ((int)(Math.random() * nImageHeight));
    DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
    inputBuffer.put(dpDataPacket);
    }

  • Using nanosleep() in a threaded program cause SIGBUS or SIGSEGV

    Greetings,
    I'm working on a multit-threaded program using Solaris' threads (not POSIX).
    When I call nanosleep() or usleep(), sometimes the program works well, but often I get either a SIGSEGV or a SIGBUS.
    Have a look at the following dbx output using a core file:
    (dbx) threads
    o>    t@1  a  l@1   ?()   signal SIGSEGV in  t_splay()
          t@2  a  l@2   cpu_thread()   LWP suspended in  ___nanosleep()
    (dbx) thread 2
    dbx: unrecognized arg/option '2'
    Use the 'help' command for more information.
    (dbx) thread t@2
    Current function is cpu_thread
      367           nanosleep(&sleep_time, NULL);
    t@2 (l@2) stopped in ___nanosleep at 0xfe5c017c
    0xfe5c017c: ___nanosleep+0x0008:        bcc,a,pt  %icc,___nanosleep+0x18       ! 0xfe5c018c
    (dbx) list
      367           nanosleep(&sleep_time, NULL);
    (dbx)The code used to create the thread:
    thr_create(NULL, 0, cpu_thread, NULL, 0, &tid);Am I missing something?
    Any suggestions are welcome.
    Thanks,
    -Thomas

    t@1 a l@1 ?() signal SIGSEGV in t_splay() Most likely a corrupted malloc heap. Thread t@1 is crashing
    somewhere inside malloc() or free().
    Use libumem(3LIB) or dbx's access / memory checking support
    to find out where you're corrupting the malloc heap.
    t@2 a l@2 cpu_thread() LWP suspended in ___nanosleep() The nanosleeping thread isn't responsible for the crash.
    The t@1 thread is the culprit. Print a stack trace for thread t@1.

  • Multi threaded programming

    I am quite new to multi threaded programming.
    The problem I am facing in my code is as follows:
    I can instantiate 1-10 threads from my controller class. For example if my controller class generates 10 threads, 5 threads
    finish the task they are assigned to do(i.e send SMS and Update the Database) and the other 5 threads eventhough send SMS but
    get stuck when they are supposed to update the Database (this is inferred from the logs).
    Due to this problem my controller class remains in a wait state as I am using the join() method and some of the threads never
    join.
    Another interesting observation is that it always happens that the thread numbered 0-5 always get stuck at the exact point
    where database has to be updated and thread number 6-10 complete their task. Same is the case when i instantiate 2 threads, i
    thread completes its task and another thread gets stuck, again at the same point.
    I am using Connection Pooling to connect to the database.
    I am sure that the problem is with the query
    int j=dbObject.execute_pst("UPDATE table SET flag='true' WHERE message IN("+trueFlag+")",con);
    where true flag is a comma seperated string containing some ID's.
    What i cannot understand is why some of the threads (almost 50% of them), work fine with this query and the others get stuck
    (i.e. just wait at this query during runtime)

    The problem must lie in the connection, as the SQL statement is to basic to cause an endless loop inside the DBMS. If you are in doubt, try the setMaxRows() method of the Statement interface, I'm using Sybase and it also limits the number of rows processed in update and delete statements (which I'm pretty sure is buggy, but you can still try it).
    Which DBMS are you using by the way?

  • Thread program: Strange output

    Hi,
    I have written a simple thread program. Previously I was trying to print hello world in the run method, the I changed it to print the value of a static data member, but strangely its still printing hello World. However if I change the print statement in the main method, it is reflected in the output but the changes to the print statement are not. Its always hello World output. I have changed the name of file, recompile it, close the shell window, restarted the computer but always the output is hello world. Can somebody help me with that. My objetive is to prove that data segment is shred in threads.
    public class Share2 extends Thread{
    static int Data=10;
       public void run ( ) {
        Data=Data+10;
         System.out.println("Data="+Data);
      public static void main (String[ ] args ) {
        First obj=new First ( );
        obj.start ( );
        System.out.println("Data ^^^^in!!! 9999main****="+Data);
    }D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>
    Zulfi.

    public class Share2 extends Thread{
    static int Data=10;
    public void run ( ) {
    Data=Data+10;
    System.out.println("Data="+Data);
    public static void main (String[ ] args ) {
    First obj=new First ( );<<<<< what is First? >>>>>>
    obj.start ( );
    System.out.println("Data ^^^^in!!!
    n!!! 9999main****="+Data);
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>
    Zulfi.

  • Thread Programming and Condition.Await

    I'm trying to get better acquainted with threaded programming by building a mock music player. It's not going over so well
    What am I doing wrong in the code snipped below? The snippet below is inside the run() method of the MusicPlayer class.
    It seems that it simply doesn't excute as intended. The behavior I want is:
    - When in Off mode: do nothing
    - When in Playing mode: Wait until song finishes, then remove song from playlist (call PlaySong)
    - When in Pause mode: Wait (pauseTimeOut) milliseconds, and if nothing happens, go to Off mode.
    The thread runs fine, but it seems that it waits forever in whatever state it is in.
    I apologize for the weird if statements..
    while (alive) {
                   System.out.println("State: "+state);
                   switch (state) {
                   case Off:
                        System.out.println("System is off");
                        try { cond.await(); }
                        catch(InterruptedException e) { alive = false; }
                        break;
                   case Paused:
                        boolean stillWaiting=true;
                        System.out.println("Waiting..");
                        try { stillWaiting=cond.await(pauseTimeOut, TimeUnit.MILLISECONDS); }
                        catch(InterruptedException e) { alive = false; }
                        if(stillWaiting) {
                             //Do nothing
                        } else if (state == States.Paused) {
                             state=States.Off;
                        break;
                   case Playing:
                        System.out.println("Playing..");
                        if(playlist == 0) {
                             state = States.Paused;
                        } else {
                             boolean waitingEndSong=true;
                             try { waitingEndSong=cond.await(songTime, TimeUnit.MILLISECONDS); }
                             catch(InterruptedException e) { alive = false; }
                             if(waitingEndSong) {
                                  //Do nothing
                             } else if (state == States.Playing) {
                                  PlaySong();
                             break;
                        try { cond.await(); }
                        catch(InterruptedException e) { alive = false; }
                        break;
                   default:
                        alive = false;
    }

    To get better help sooner, post a SSCCE that clearly demonstrates the problem.
    Use 2 to 4 spaces, not tabs, for indentation. Most members won't take the trouble to read code that is too deeeply indented. I know I don't.
    luck, db

  • Need help with java thread program

    Hi
    I have an applet which does some painting etc, i need to write a thread which runs in background, and if there is no user activity for 30 min will refresh the screen.
    I have one good thing that all user options go from one program so i know when user does some thing.
    How do i write this thread program?
    1. I need this program to start counter as soon as some activity is done by user
    2. When user does some thing stop this thread
    3. when user completes his action restart the thread with 30 min timer.
    4. when there is no activity for 30 min refresh the screen
    Any help will be really good
    Ashish

    Not sure what the problem is. Your pseudo code looks good to me.
    The only suggestion I would make is that your use a Timer so you don't have to worry about creating your own Thread. You schedule a Timer to fire in 30 minutes. Everytime you have activiity you cancel the timer and reschedule it.

  • Single Threaded Program

    What do you mean by a single threaded program?? For example I have a single threaded word processor which can do only one task at a time. Does this mean that there is one and only thread which is carrying out all tasks one at a time??Say,formatting the document and then printing??I think I'm very near to it but not getting it properly.Please help.Thanks a lot.

    A single threaded program is a normal program that has only one thread. That doesn't mean that it can do only one task at a time, but that one thread is performing all the tasks.

  • HELP!....GUI crashes when i call a multi-threaded program from it

    Hi..I have encountered a problem in my end of year project, which i cant see to solve. The problem is i am starting a multi-threaded program for a JButton on a GUI. All though this starts the other program it crashes the GUI completely how do i stop this.
    this is the code i use to call the threaded program.
    public void actionPerformed(ActionEvent e)
    Object target=e.getSource();
    String line = new String();
    if( target==b1 )
         try
    cl = new client();
         cl.startup();
         catch(Exception ex){ex.printStackTrace();}
    thanks Mike

    No there is no exceptions being given. this is one of the reasons why i dont no what to do. i thought myself that the threaded was taking all the resources and not going back to the GUI. if this is the case is there anyway that i can call back the GUI and keep the threaded program running?
    thanks
    mike.

  • Paul Hyde's Java Thread Programming

    I have Paul Hyde's Java Thread Programming and I am wondering if it is a comprehensive book for learning the nuts n bolts of threads. I know how to use threads however I want to learn the inner details. Doug Lea's book is perhaps a better option but Paul Hyde's book seems more readiable.
    Any comments are appreciated.
    cheers

    Sounded interesting, found this link
    http://www.javaspecialists.co.za/archive/Issue056.html

  • Problem with threads, program always crash

    new to threads, may be doing something COMPLETELY wrong. When I run the program I get a couple of NullPointerExceptions in Thread-0 and Thread-1. I'm confused because it screws up when I call size() for arrayList, and in the API size doesn't throw anything.
    public class ProducerConsumerRunner
       public static void main(String args[])
          Queue q = new Queue(QUEUE_MAX_SIZE);
          ProducerRunnable producer = new ProducerRunnable(q, ITERATIONS);
          ConsumerRunnable consumer = new ConsumerRunnable(q, ITERATIONS);
          //works good up to here
          Thread t1 = new Thread(producer);
          Thread t2 = new Thread(consumer);
          t1.start();
          t2.start();
       private static int ITERATIONS = 50;
       private static int QUEUE_MAX_SIZE = 25;
    import java.util.ArrayList;
    import java.util.concurrent.locks.ReentrantLock;
    public class Queue {
         public Queue(int maxSize)
              list = new ReentrantLock();
              underLimit = list.newCondition();
              MAX_SIZE = maxSize;
         public void add(String line)
              list.lock();
              try{
                           System.out.println("add method of Queue");
                   while(record.size() >= MAX_SIZE){//things get screwed up when this condition is evaluated
                        //size method is crashing the program
                        System.out.println("2");
                        underLimit.await();
                        System.out.println("3");
                   record.add(line);
              }catch(java.lang.InterruptedException e){
                   System.out.println("await interupted: "+e.getMessage());
              }finally{
                   list.unlock();
         public void remove(int line)
              list.lock();
              record.remove(line);
              list.unlock();
         public  ArrayList<String> record;
         private final ReentrantLock list;
         private final java.util.concurrent.locks.Condition underLimit;
         private final int MAX_SIZE;
    import java.util.Date;
    public class ProducerRunnable implements Runnable{
         public ProducerRunnable(Queue q, int itterations)
              this.q = q;
              ITTERATIONS = itterations;
         public void run()
              String date;
              for(int i = 0; i<ITTERATIONS; i++)
                   date = new Date().toString();
                   q.add(date);//this is where it screws up
                   System.out.println(date+" added");
                   try{
                   Thread.sleep(100);
                   }catch(java.lang.InterruptedException e){
                        System.out.println("ProduccerRunnable's sleep was interupted");
         private final Queue q;
         private final int ITTERATIONS;
    public class ConsumerRunnable implements Runnable{
         public ConsumerRunnable(Queue q, int itterations)
              this.q = q;
              ITTERATIONS = itterations;
         public void run()
              //Queue q = new Queue();
              int length;
              for(int i = 0; i<ITTERATIONS; i++)
                   length = q.record.size();//things are getting screwed up here
                   while(q.record.get(length) == null)
                        length--;
                   System.out.println((String)q.record.get(length));
                   q.remove(length);
                   try{
                   Thread.sleep(100);
                   }catch(java.lang.InterruptedException e){
                        System.out.println("ConsumerRunnable's sleep was interupted");
         private final Queue q;
         private final int ITTERATIONS;
    }

    question:
    this works right
         public void remove()
              list.lock();
              int line = 0;
              try{
                   *while(record.size() < 1)*
                        range.await();
                   record.remove(line);
                   range.signalAll();
              }catch(java.lang.InterruptedException e){
                   System.out.println("await interupted: "+e.getMessage());
              }finally{
                   list.unlock();
         }this is deadlock
    *int list = 0;*
    *while((list = record.size)<1) was screwing things up because of the assignment*record is ArrayList of strings. when better to use Vector instead of ArrayList? i notice no differnce and i use threads
    initially I thought record.size was being evaluated and before could be assigned to list, time slice ran out. this could not be case because I use ReentrantLock (list) to lock it.
    Edited by: bean-planet on Apr 1, 2009 4:31 PM

  • Sinlge-thread program in multiple Java VM.

    I have a program that spawns two threads: one reads text line by line from a file, and places it in a LinkedBlockingQueue; The other takes stuff off the LinkedBlockingQueue, and processs it (no output to other file). Therefore this is a typical Producer and Consumer setup. I use two threads for one each. The program is run from Windows XP command window.
    It runs fine. Processes big text files as expected, even though the CPU % is kind of high. Then, just for fun, I started five command windows to run one instance in each, but with different files. CPU % in task manager spikes to 100%, and the processing in each window slows down dramatically, to only about 2000 rows in every 30 or 40 seconds.
    The code posted below is actul code of the program. Runs fine in single command window but terribly slow in multiple windows (with different data file.). The getAnswer() is a bad stuff. I should have had used Callable instead but it is not important.
    Can anyone review the code and let me know what is the cause of slowdown, or I just should run it in mulitple instances in multiple command windows?
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.*;
    // --------- file reading thread ----------------------
    class fReader implements Runnable {
    private LinkedBlockingQueue<ArrayList<String>> q=null;
    private String input_f=null;
    private BufferedReader br=null;
    private int total=0;
    public fReader(LinkedBlockingQueue<ArrayList<String>> q, String filename) throws IOException {
    q=_q;
    input_f=file_name;
    br=new BufferedReader(new FileReader(input_f));
    public int getAnswer(){return total;}
    public void run(){
    ArrayList<String> tb=new ArrayList<String>();
    String s=null;
    try {
    while(true){
         for (int z=0; z<200; z++) {
              s=br.readLine();
              if (s==null) break;
              total++;
              tb.add(s.trim());
         if (s==null) break;
         q.put(tb);
         tb=new ArrayList<String>();
         Thread.yield();
    tb.add(s);
    q.put(tb);
    br.close();
    catch(IOException e1){}
    catch(InterruptedException e2){}
    // ----- file processing thread ----------
    class fProc implements Runnable {
    private LinkedBlockingQueue<ArrayList<String>> q=null;
    private String output_f=null;
    private PrintWriter pw=null;
    private String match=null;
    private int total=0;
    public fProc(LinkedBlockingQueue<ArrayList<String>> q, String filename, String match_s) throws IOException {
    output_f=file_name;
    q=_q;
    pw=new PrintWriter(new BufferedWriter(new FileWriter(output_f)));
    match=match_s;
    public int getAnswer(){return total;}
    public void run(){
    ArrayList<String> p=null;
    boolean busy=true;
    while(busy){
         p=q.poll();
         if (p==null) {
              Thread.yield();
              continue;
    // loop, count, and print at the end of the processing
         Iterator ir=p.iterator();
         while(ir.hasNext()){
              String x=(String)ir.next();
              ir.remove();
              if (x==null){
                   busy=false; break;
              else {
                   String[] m=x.split("[,]");
                   String[] n=m[2].split("[\"]"); // null(0), something(1), null(0)
                   if (n[1].equals(match))
                        total++;
              Thread.yield();
         p=null;
         System.out.println("Processing");
    if (pw!=null) pw.close();
    // end of run()     
    // end of class
    public class pf2 {
    private String date_value=null, fn_ext=null;
    private File _file=null;
    private File _dest=null;
    public pf2(){_file=null;_dest=null;}
    // -------------- application start point ----------------
    public static void main(String[] args) throws IOException{
    if (args.length!=1){
         System.out.println("Usage: java pf2 <filename.ext>");
         System.out.println("Example: java pf2 vwo.2011-01-18.csv");
         return;
    String inputf=".\\original\\"+args[0];// args[0] is the filename with extension.
    String outputf=".\\data\\"+args[0];// args[0] is the filename with extension.
    // split the date string in input file name.
    String[] date_s=args[0].split("[.]+")[1].split("[-]+");
    String date2=String.format(
         "%s/%s/%s",
         Integer.toString(Integer.parseInt(date_s[1])),
         Integer.toString(Integer.parseInt(date_s[2])),
         Integer.toString(Integer.parseInt(date_s[0]))
    ExecutorService es=Executors.newFixedThreadPool(4);
    LinkedBlockingQueue<ArrayList<String>> q=new LinkedBlockingQueue<ArrayList<String>>();
    fReader input=null;
    fProc output=null;
    try {
         input=new fReader(q, inputf);
         output=new fProc(q, outputf, date2);
    catch(IOException e3){
         System.out.println(e3.getMessage());
         return;
    // starts the program here
    System.out.println("Running ....");
    es.execute(input);
    es.execute(output);
    es.shutdown();
    while(!es.isTerminated());
    System.out.printf("Read %d row(s), %d of them are good.\n", input.getAnswer(), output.getAnswer());
    float v=new Integer(output.getAnswer()).floatValue()/new Integer(input.getAnswer()).floatValue();
    System.out.printf("Bad rate=%.2f%%.\n", (1-v)*100);
    System.out.print("Press a key to continue.");
    while(System.in.read()==-1);
    // end of main()
    // end of class pf
    }

    As @EJP suggests, disk work best when read serially. When the OS detects you are reading a file serially it will prefetch the next data you need. You may find that removing the reader thread is faster as you are doubling up what the OS does for you.
    However, when you read multiple files from the same disk the head has to move around more, slowing it down significantly. I would suggest only using multiple readers when you have multiple independent disks. (Though I have never seen this work well on Windows, only on Unix)

  • Threaded program takes more time than running serially!

    Hello All
    Ive converted my program into a threaded application so as to improve speed. However i found that after converting the execution time is more than it was when the program was non threaded. Im not having any synchronised methods. Any idea what could be the reason ?
    Thanx in advance.

    First, if you are doing I/O, then maybe that's what's taking the time and not the threads. One question that hasn't been asked about your problem:
    How much is the time difference? If it takes like 10 seconds to run the one and 10 minutes to run the threaded version, then that's a big difference. But if it is like 10 seconds vs 11 seconds, I think you should reconsider if it matters so much.
    One analogy that comes to mind about multiple threads vs. sequential code is this:
    With sequentially run code, all the code segments are lined up in order and they all go thru the door one after the other. As one goes thru they all move up closer, thus they know who's going first.
    With multi-threaded code, all the code segments sorta pile up around the door in a big crowd. Some push go thru one at a time while others let them (priority), while other times 2 go for the door at the same time and there might be a few moments of "oh, after you", "no, after you", "oh no, I insist, after you" before one goes thru. So that could introduce some delay.

  • Threaded program takes more time than executing serially!

    Hello All
    Ive converted my program into a threaded application so as to improve speed. However i found that after converting the execution time is more than it was when the program was non threaded. Im not having any synchronised methods. Any idea what could be the reason ?
    Thanx in advance.

    Putting aside fstreams amusing comment, I suspect your
    theads are never yielding (they are sitting in a tight
    loop, thus taking all available procesor power). Try
    adding Thread.sleep(0) at som point in the loop.No. If you just want to encourage one thread to give another thread a turn, use yield, not sleep.
    Note, though, that this may not help your situation. As was pointed out, on a single CPU machine, the only way a multithreaded program will run faster (by which I mean total wall-clock time start to finish) than its single-threaded equivalent is if the 1-thread version spends a lot of time waiting for IO when it could be doing something else. (If it's waiting for IO, but that IO is needed for the big number crunching, then putting the crunching in another thread won't make things any faster.)
    On the other hand, if by "faster" you're referring to a more responsive GUI, then, yes, in general you might expect better GUI response be putting non-GUI stuff in a different thread, but there's no guarantee. Depending on what the other thread does, how much work your GUI has to do, how your VM's scheduler works, how you've split up the work, etc., it may not be any better.
    I know that's not very specific, but neither was your question.

  • How can I use select() function in POSIX thread program.

    Hello
    Now I making a my own progam with POSIX thread in Solaris 8 Environment.
    But I have some trouble in POSIX thread.
    I saw that If use POSIX thread then use -D_POSIX_C_SOURCE=???L flag into compile options in
    Multithreaded Programming Guide.
    So I use that in my Makefile. But I can't compile my program.
    Now I found that if use POSIXC_SOURCE flag, cannot use timeval structure (defined in <sys/time.h>) in <sys/resource.h>.
    So compiling was stop into select() function. Because select() function use timeval structure.
    And fd_set structure(defined in <sys/select.h>) is same.
    How I solve this problem.
    Please help me.
    Thank you.

    Thanks so much for your helpful reply.
    Now I' ve already installed Adobe Creative Suite 6 Production Premium (Student Package), Extended included. But when I open Photoshop CS6, there' s still no 3D function in menu bar.
    Would you please tell me how to activate this function?
    Thanks,

Maybe you are looking for

  • So, I accidentally left my iPod 4 face down in a puddle of water all night. . . :(

    This morning I decided to check my email on my iPod and picked it up and found two tablespoons of water pooling under it from where I knocked over my drink last night. I dried it off and left it to air dry, I left the buttons alone and tried not to t

  • How to integrate FOP into C# solution

    hello i work with VS2008 C#. and i have fop-0.95beta witch make a pdf files from XML and XSL. i want to know how to integrate fop into my solution, and how to work with C#. thanks a lot

  • OIM wizard can't contact WebLogic at t3://my.hostname.me:7001

    I am running the OIM configuration wizard on a Linux machine and I can't get weblogic to see that OIM is installed in the only domain I have on the box. I'm on the screen where I'm being asked to specify the WebLogic Admin Server url beginning with t

  • Site not visible in IE8

    This is the 4th site I've done in DW and for some reason it's not visible in IE8. Looks fine in FireFox. www.giselleaguiar.com I changed the meta tag to: meta http-equiv="X-UA-Compatible" content="IE=7;FF=3;OtherUA=4" /> and still nothing. What am I

  • Crashing whenever using mx.controls.Alert.show

    Flex Project: Desktop (AIR) Flex SDK: 4.1 Flash Builder 4 Problem: Whenever I use Alert.show even with the simplest strings passed it crashes showing the following error: TypeError: Error #1009: Cannot access a property or method of a null object ref