Threads yielding;

I'm new to this forum so I don't know if it's frowned upon to post lengthy(for me anyway!) code snippets. If it is tell me and I won't do it again.
Anyway.............
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Viewer extends JFrame{
DisplayPanel[] panels;
DisplayThread[] display_Threads;
boolean[] running;
int selected;
DisplayListener listener;
public Viewer(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
JLabel topLabel = new JLabel("Viewer");
topPanel.add(topLabel);
listener = new DisplayListener();
JPanel mainPanel = new JPanel(new GridLayout(1,2));
contentPane.add("North", topPanel);
contentPane.add("Center", mainPanel);
panels = new DisplayPanel[2];
display_Threads = new DisplayThread[2];
running = new boolean[2];
for (int i = 0; i < display_Threads.length; i++){
panels[i] = new DisplayPanel("Panel " + (i + 1));
panels.addMouseListener(listener);
running[i] = false;
mainPanel.add(panels[i]);
setSize(400, 400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
class DisplayListener extends MouseAdapter{
public void mousePressed(MouseEvent e){
if (e.getSource().toString().equals("Panel 1")) {
selected = 0;
if (!running[selected]) {
display_Threads[selected] = new DisplayThread();
display_Threads[selected].start();
running[selected] = true;
else {
display_Threads[selected] = null;
running[selected] = false;
else {
selected = 1;
if (!running[selected]) {
display_Threads[selected] = new DisplayThread();
display_Threads[selected].start();
running[selected] = true;
else {
display_Threads[selected] = null;
running[selected] = false;
class DisplayThread extends Thread{
public DisplayThread(){
public void run(){
Thread currentThread = Thread.currentThread();
while (display_Threads[selected] == currentThread){
try{
Thread.sleep(100);
} catch (InterruptedException e) {}
panels[selected].updatePosition();
panels[selected].repaint();
public static void main(String[] args){
Viewer viewer = new Viewer();
class DisplayPanel extends JPanel{
String name;
int x, y, vel;
public DisplayPanel(String name){
this.name = name;
x = y = 50;
setBackground(Color.lightGray);
setForeground(Color.black);
setBorder(new LineBorder(new Color(204, 204, 204), 3));
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(name, 50+vel, 50);
System.out.println("Paint");
public String toString(){
return name;
public void updatePosition(){
vel++;
When I click on Panel 1 the "Panel 1" string scrolls across the screen.
When I cli1ck on Panel 2 , the first string stops scrolling and the second one starts.
Why does the first one stop when I haven't stopped the Thread.
I'm wondering how to get them both to keep moving at the same time.
Any ideas?

I'm new to this forum so I don't know if it's frowned
upon to post lengthy(for me anyway!) code snippets. If
it is tell me and I won't do it again.
Anyway.............
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Viewer extends JFrame{
   DisplayPanel[] panels;
   DisplayThread[] display_Threads;
   boolean[] running;
//why create an array of panels, threads, and boolean?
   int selected;
//what does the selected variable do?
   DisplayListener listener;
//ok, this is a listener class
//contructor
   public Viewer(){
     Container contentPane = getContentPane();
     contentPane.setLayout(new BorderLayout());
     JPanel topPanel = new JPanel();
     JLabel topLabel = new JLabel("Viewer");
     topPanel.add(topLabel);
//what does the DisplayListener class do?
     listener = new DisplayListener();
JPanel mainPanel = new JPanel(new
new GridLayout(1,2));
     contentPane.add("North", topPanel);
     contentPane.add("Center", mainPanel);
//creating an array of data members is gettin me lost?  Why not create an array classes that has all the variables you need for a single object?
     panels = new DisplayPanel[2];
     display_Threads = new DisplayThread[2];
     running = new boolean[2];
     for (int i = 0; i < display_Threads.length; i++){
panels[i] = new DisplayPanel("Panel " + (i +
  (i + 1));
       panels.addMouseListener(listener);
running[i] = false;
mainPanel.add(panels[i]);
setSize(400, 400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
class DisplayListener extends MouseAdapter{
public void mousePressed(MouseEvent e){
if (e.getSource().toString().equals("Panel 1"))
"1")) {
selected = 0;
if (!running[selected]) {
display_Threads[selected] = new
ed] = new DisplayThread();
display_Threads[selected].start();
running[selected] = true;
else {
display_Threads[selected] = null;
running[selected] = false;
else {
selected = 1;
if (!running[selected]) {
display_Threads[selected] = new
ed] = new DisplayThread();
display_Threads[selected].start();
running[selected] = true;
else {
display_Threads[selected] = null;
running[selected] = false;
This is your thread class. The run dedicates what the thread does. Now, you are probably creating only one thread. What not create two threads? One thread in your code only operates one GUI, panel, or frame at a time. So, create two threads. Panel1 would be handle by thread1. Panel2 would be handle by thread2. Now, it comes down to the run method. The ran method can be modified to tell the thread which GUI to handle.
class DisplayThread extends Thread{
public DisplayThread(){
public void run(){
Thread currentThread = Thread.currentThread();
while (display_Threads[selected] ==
== currentThread){
try{
Thread.sleep(100);
} catch (InterruptedException e) {}
panels[selected].updatePosition();
panels[selected].repaint();
public static void main(String[] args){
Viewer viewer = new Viewer();
class DisplayPanel extends JPanel{
String name;
int x, y, vel;
public DisplayPanel(String name){
this.name = name;
x = y = 50;
setBackground(Color.lightGray);
setForeground(Color.black);
setBorder(new LineBorder(new Color(204, 204, 204),
4), 3));
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(name, 50+vel, 50);
System.out.println("Paint");
public String toString(){
return name;
public void updatePosition(){
vel++;
When I click on Panel 1 the "Panel 1" string scrolls
across the screen.
When I cli1ck on Panel 2 , the first string stops
scrolling and the second one starts.
Why does the first one stop when I haven't stopped he
Thread.
I'm wondering how to get them both to keep moving
the same time.
Any ideas?
You probably only create one thread to handle both
GUI panels. Create two threads instead. One thread
handles Panel1, the other thread handles Panel2.
Again, modifiy your run method to dictact which GUI
to hanle:
For example:
//..in your thread class
void run(boolean whichGUI){
   if (true)
      Panel1 run it!
   else
      Panel2 run it!
}Remember, you need to create two threads for each
panel.

Similar Messages

  • Thread yield() and sleep()

    what is the different bettween yield() and sleep() method
    in thread
    i think sleep() method make the called thread to wait then
    make the way to enter any other
    but yield() also do same but dont allow lower priority threads
    allow only higher priority thread.
    is this correct?

    Thread.yield() is used to give other threads a chance to get a processor time slice, according to the thread dispatcher rules. If there are no other threads ready to run, the current thread will gain the processor again.
    Thread.sleep() will always release the processor for at least the amount of time specified, even if there are no other threads requesting it.

  • Thread.yield() and Thread.sleep(), what's the difference

    Folks'es,
    can anyone enlighten me, as to the difference between yield() and sleep() in the Thread class?
    i know, with sleep, one can specify the amount of time to sleep, but does that mean the thread yields for that amount of time?
    if i use yield(), how long will my thread stop running?
    any information is appreciated
    thomas

    Thread.yield() is used to give other threads a chance to get a processor time slice, according to the thread dispatcher rules. If there are no other threads ready to run, the current thread will gain the processor again.
    Thread.sleep() will always release the processor for at least the amount of time specified, even if there are no other threads requesting it.

  • Thread.yield inquiry

    Guys,
    Based on the definition of Thread.yield
    yield() function causes the currently executing thread object to temporarily pause and allow other threads to execute.
    But how if "Thread1" (just for name of the Thread) calls Thread.yield() and at that time I only got one thread (Thread1 only), will this thread stop for awhile also?
    Thanks

    I don't really understand what you are asking but stay away from Thread.yield, you can't test the performance of such code because it will be dependant on the jvm implementation. As Joshua Bloch says in Effective Java - "The only use that most programmers will ever have for Thread.yield is to artificially increase the concurrency of a program during testing". Think of Thread.yield as just a hint to the scheduler.
    Edit: If you are asking what will happen when you call yield on the currently executing thread with no other threads to execute - you will likely get control back immediately.

  • Thread yields cpu WITHOUT forcing process to lose cpu

    I would like to know how a thread should yield the CPU without forcing its process to lose the CPU. The candidates are thr_yield, sched_yield and yield.
    "The yield() function causes the current lightweight process to yield its execution in favor of another lightweight process with the same or greater priority." This looks promising if the LWP is bound to the thread in question, but I still don't know what would happen if the thread has process contention scope.
    "The sched_yield() function forces the running thread to relinquish the processor until the process again becomes the head of its process list. It takes no arguments." Yuck! Does this mean that the process is booted by the operation? I would have preferred it if no mention of process had been made."
    "The thr_yield() function causes the current thread to yield its execution in favor of another thread with the same or greater priority." Perhaps the best candidate. This does, of course, push us in a direction away from portability unlike sched_yield.
    I was just wondering if anyone knew the answer to this question. Thanks in advance to anyone who takes the time to reply.
    Sincerely,
    jonnie savell

    Hi,
    without AWR/ASH your options for retrospective troubleshooting are very limited. You can use statspack -- but unlike AWR, it requires the DBA to either launch it manually, or manually schedule a database job for this purpose.
    V$ views won't help you because they either represent statistics accumulated since the last instance startup, or the current state of the database (like V$SQL which externalizes the current contents of the library cache -- so if a cursor is aged out, you won't find it there). What you need is differential stats -- i.e. differences between snapshot (e.g. before and after a problem), there are no default mechanisms in the database for that (other than AWR or analogs).
    You query is meaningless because:
    - cursors may have been aged out
    - cursors may have later last_load_time (because after being executed in the specified interval, they may have been active at a later time)
    - even if you managed to get an accurate number of cursors accessed during a certain interval, what would you do with it?
    Pretty much your only option is to do log mining, if you have archived logs for the period of interest. It's time consuming, but it will give you the entire history of all SQL run, if you really need it.
    Best regards,
    Nikolay

  • Thread.sleep and Thread.yield

    hi,
    anyone knows the difference between these 2 methods ?
    so far as i can see, the only diff is that sleep takes in an argument (time in millis) whereas yield does not.
    also, both methods hold on to the locks and dont give them up.
    pls comment

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#sleep(long)
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#yield()
    pretty clear...

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Image repaint preformance and threading

    Folks,
    I'm trying to make this sucker run faster.
    My question is, can anyone please guide me, especially with regards synchronising the Threads more efficiently... I'm thinking of using join and i]notify to make the "navigator" threads yield to the swing threads, to give it a chance to repaint before continuing... does this sound sane to you?
    Currently, without the thread.sleep it paints get the first "burst", and then nothing until the alrorithm has completed... exactly not what I wanted, because the whole point of this GUI is to watch the algorithm at work... sort of a "visual debugger"... I find that watching an algorithm play out helps me to "imagineer" ways of improving it... and in this case improvement means optimisation... it's all about getting from A-J faster than anyone else on the planet, especially those smarty-wishbone-legs C# programmers ;-)
    The code is too big to post (darn that 7500 char limit!) so I'll split it over several posts here, and I've also posted it as a single download to [MazeOfBoltonGUI2.java|http://groups.google.com/group/comp_lang_java_exchange/web/MazeOfBoltonGUI2.java] on my google group (comp lang java exchange).
    Cheers all. Keith.
    package forums.maze;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.SortedMap;
    import java.util.TreeMap;
    import java.util.Stack;
    import java.util.Queue;
    import java.util.PriorityQueue;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    * A Visual debugger,
    * for the [A* Alogorithm|http://en.wikipedia.org/wiki/A*_search_algorithm] navigator
    * of the [Maze Of Bolton|http://cplus.about.com/od/programmingchallenges/a/challenge12.htm]
    * as implemented by [Prometheuz|http://forums.sun.com/profile.jspa?userID=550123]
    * with GUI by [Kajbj|http://forums.sun.com/profile.jspa?userID=91610]
    * hacked together by [Keith Corlett|http://forums.sun.com/profile.jspa?userID=640846]
    * and posted on [Sun's Java Forum|http://forums.sun.com/thread.jspa?threadID=5319334]
    * and posted on [Google news group|http://groups.google.com.au/group/comp_lang_java_exchange/]
    public class MazeOfBoltonGUI2
      static final char[][] matrix = readMatrix("map.txt");
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                MazeNavigator navigator = new MazeNavigator(matrix);
                JFrame frame = new JFrame("MazeOfBoltonGUI2");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new MainPanel(navigator));
                frame.pack();
                frame.setVisible(true);
              } catch (Exception e) {
                e.printStackTrace();
       * Reads the file into a char matrix[rows,cols] ie: an array of char arrays.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      private static char[][] readMatrix(String filename) {
        try {
          BufferedReader input = null;
          try {
            input = new BufferedReader(new FileReader(filename));
            char[][] matrix = null;
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ( (line = input.readLine()) != null ) {
              lines.add(line);
            int rows = lines.size();
            matrix = new char[rows][];
            for (int i=0; i<rows; i++) {
              matrix[i] = lines.get(i).toCharArray();
            System.err.println("DEBUG: rows="+rows+", cols="+matrix[0].length);
            return matrix;
          } finally {
            if(input!=null)input.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new IllegalStateException("Failed to readMatrix!", e);
    class MainPanel extends JPanel
      private static final long serialVersionUID = 1L;
      // button panel
      private final JButton goButton;
      // maze panel
      private final MazeNavigator navigator;
      private final Monitor<Path> monitor;
      private BufferedImage background;
      private BufferedImage image;
      private List<Path>currentPaths;
      public MainPanel(MazeNavigator navigator) {
        this.navigator = navigator;
        this.monitor = new SwingMonitor();
        this.goButton = new JButton("Go");
        goButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              final String caption = goButton.getText();
              goButton.setVisible(false);
              monitor.execute();
        add(goButton);
        setPreferredSize(new Dimension(navigator.maze.cols*3, navigator.maze.rows*3)); //w,h
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      private static Color[][] mazeColors;
      private static Color[][] createMazeColors(Maze maze) {
        Color[][] colors = new Color[maze.rows][maze.cols];
        for (int r=0; r<maze.rows; r++) {
          for (int c=0; c<maze.cols; c++) {
            colors[r][c] = getColor(maze.matrix[r][c].ch);
        return colors;
      }*... PTO ...*

    I'm persuaded that the main issue (no intermediate results drawn) is the improper use of SwingWorker.
    When you've got over it, you may want to consider other smaller-effect optimizations:
    Reconsider usage of an offscreen image*
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      }At first I didn't get why you wanted to draw an offscreen image, then paint it to the screen, all that in the EDT.
    After reading the draw() method more closely, I guess you want to ease the coding of the scaling: you draw an image where one cell = one pixel, then paint the image, scaled to the panel's display size.
    In terms of performance, I don't know how it stands:
    On one hand, the image creation if lighter (1 pixel per cell). And you have a point that the built-in scaling offered by Graphics2D.drawImage(image, size) may be efficient. I can't comment on that, I hope the granphics and hardware acceleration folks will pop in the thread.
    On the other hand, if the built-in scaling had poor performance, it may be good to try what "manual" scaling would bring you. That means, in a simplified version, skip the offscreen image creation, and draw directly on the paintComponent()'s Graphics2D argument. the drawing of a cell at coordinates c,r, for example, would look like:
    g.fillRect(c*CELL_WIDTH, r*CELL_HEIGHT, WIDTH, HEIGHT);Performance apart, the scaling as you do it currently has functional drawbacks, if you want pathes as 1-pixel width lines over large cells:
    - if the maze is smaller (in rows, columns) than the panel displaying it (in pixels), the cells will be scaled but the pathes too: so your 1-pixel lines appear as large as the cells. May or may not be a desired effect.
    - if the maze is larger than the display panel, the cells are shrinked, fine, but the so are the path lines, to a point where they may be invisible (probably depending on color blending, I'm a n00b at graphics operations).
    But maybe I misunderstood the need, and maybe the intended drawing of a path is actually the drawing of the rectangles of all its traversed cells, in special path colors?
    Reconsider intermediate allocations*
    Each paintComponent() call results in the allocation of a 2D-array of Color objects (method createMazeColors(Maze)).
    I don't see what the mazeColors array brings you. I assume you wanted to decouple the determination of colors (depending on cell state) and the rendering of the colors: what does it bring: no performance advantage (on the contrary, it adds a 2D array allocation, and 2xN^2 2D-array access), and does not improve the code readability either (subjective rant, sorry).
    Why don't you pass the Maze as an argument to the draw() method, and call the getColor(cell.ch) from there?
    Side note, maybe a bit subjective: performance apart, the design of the usage of this mazeColor array is a no-go!
    An instance method alters a static variable reference,which is used subsequently in another instance method, with no synchronization. The current code does that in a single thread (+paintxxx()+ is only called in the EDT), which keeps that safe (I'd dare to say: by luck), but considerations exposed below may have you refactor the design to introduce other threads, and may exhibit the thread-unsafety of this design.
    Consider drawing the image in a background thread.*
    Indeed the technique of drawing to an offscreen image is quite common, but it is often done to improve responsiveness (not raw performance) of Swing applications. Here is a resource about this (what the author calls the passive approach), although it doesn't use a background thread.
    The idea is that if a paintCompobnent() methods involves lots of computation (arithmetics of traversing a 2D model, scaling things, etc.), this takes CPU times in the EDT, and all subsequent events (such as, a MouseEvent, but also other painting events) keep pending on the event queue, which is consumed by the single event-dispatch thread. The result is that the UI appear unresponsive, and painting of other areas may seem hung.
    The idea is to move the computation to a background thread, which posts rendering to the EDT when the Image is ready to be displayed.
    Of course this doesn't gain any CPU time. This only ensures the EDT uses a minimal part of this CPU (only render and image and process events), instead of performing the whole computation.
    In your case you already have a background thread, and indeed an appropriate choice, a SwingWorker. The application of this technique would consist in calling the draw() method in the worker thread (in the update(Path) method), and invoke super.publish() only after the image has been updated. Note that the process(List<Path>) could then ignore its argument (you may reconsider the choice of type parameter of the worker), and simply get the latest version of the image attribute).
    Of course in this technique, the offscreen image filling is called synchronously from the Navigator, so this halts the algorithm part itself, for the duration of the image generation. You may refine the technique by spawning a dedicated thread for the image generation - with subtle guard code to handle occasions when the algorithm goes faster than the image generation, and posts a new update(Path) while the image generation for the previous path has not completed yet...
    Recuce the number of things to redraw*
    Two parts:
    first, depending on the number of cells and pathes, there may be (yet another) optimization, to not redraw the whole offscreen image, but only the cells/path that have changed in the last update(). In particular, if a path is not a line but a list of cells, then it's quite easy, reusing the current offscreen image, to only fillRect(...) the appropriate cells.
    Second, if a path is not rendered as a thin line over larger cells, but as cells themselves rendered in special path colors, you may paint cells and path in one go: instead of drawing, first the cells, then the path, draw only the cells, electing the color using a decision method such as:
    private Color getColor(Cell) {
        if (cell.getPathState()!=NOT_IN_ANY_PATH) {
            return getColor(cell.getPathState());
        else {
            return getColor(cell.ch);
    }Of course this forces you to modify your data model, and update the new pathState as part of the algorithm (or better isolated, in the update(Path) method, before invoking the drawing machinery). Maybe that was the intention of the mazeColors array?
    I haven't studied your other posts on the logic of the MazeOfBolton algorithm, so I don't know if it's acceptable for you that a cell appear to have only one path state, as opposed to one for each of the pathes that traverse it. This last trick may then seem incorrect, but please consider it as only a graphical information, and indeed your current image drawing draws only ONE path for a given cell (the last path in currentPaths that traverses this cell ).

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • New Socket takes too long / how to stop a Thread ?

    Hello to everyone,
    I have a problem that I have been hunting this ol' Sun website all day for a suitable answer, and have found people who have asked this same question and not gotten answers. Finally, with but a shred of hope left, I post...
    My really short version:
    A call to the Socket(InetAddress,int) constructor can take a very long time before it times out. How to limit the wait?
    My really detailed version:
    I have a GUI for which the user enters comm parameters, then the program does some I/O while the user waits (but there is a Cancel button for the Impatient), then the results are displayed. Here is quick pseudocode (which, by the way, worked great before there were Sockets in this program -- only serial ports):
    Main (GUI) thread:
         --> reset the stop request flag
         --> calls workerThread.start(), then brings up a Cancel dialog with a Cancel button (thus going to sleep)
         --> (awake by dialog closing -- dialog may have been closed by workerThread or by user)
         --> set stop request flag that worker thread checks (in case he's still alive)
         --> call workerThread.interrupt() (in case he's alive but asleep for some reason (???))
         --> call workerThread.join() to wait for worker thread to be dead (nothing to wait for if he's dead already)
         --> display worker thread's result data or "Cancelled..." information, whichever worker thread has set
    Worker thread:
         --> yield (to give main thread a chance to get the Cancel Dialog showing)
         --> do job, checking (every few code lines) that stop request flag is not set
         --> if stop request, stop and set cancelled flag for Main thread to handle
         --> if finish with no stop request, set result data for Main thread to handle
         --> take down Cancel Dialog (does nothing if not still up, takes down and wakes main thread if still up)
    THE PROBLEM: Worker thread's job involves doing IO, and it may need to instantiate a new Socket. If it is attempting to instantiate Socket with bad arguments, it can get stuck... The port int is hardcoded by the program, but the IPAddress must be typed by user.
    If the arguments to Socket(InetAddress, int) constructor contain a valid-but-not-in-use IP address, the worker thread will get stuck in the Socket constructor for a LONG time (I observed 1m:38s). There is nothing the Main thread can do to stop this wait?
    EVEN WORSE: If the user clicks the Cancel Button during this time, the dialog goes away soon/immediately, but then the GUI appears to be hanging (single-threaded look) until the long wait is over (after which the "Cancelled..." info is displayed).
    MY QUESTION: Is there nothing the Main thread can do to stop this wait?
    Your answers will be sincerely appreciated. Despite my hopeless attitude (see above), the folks at this forum really have yet to let me down ...
    /Mel

    http://developer.java.sun.com/developer/technicalArticles/Networking/timeouts/

  • Multiple threads calling the same stored proc with different parameters

    Hi,
    I have a stored procedure which will be called by 8 threads. Every time it takes in a different parameter.
    Actual execution time for this proc (irrespective of the parameter) is around 2 seconds. But when I call the 8 threads, I see that the total time taken (END TO END) is around 16 seconds. Threads do acquire a read lock right? Is there a way i can get over this issue?
    Please let me know.

    Sybase IQ is the database. I am using a thread pool. The time taken to execute this procedure without threads is about 2 seconds. It takes 16 seconds when I start using threads.
    I do something like this :
    ///////////////////////// databaseThreadPool.java
    * example of a fixed-size thread pool using the
    * executors introduced in Java 5
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class databaseThreadPool
    public static void main(String[] args)
    * create a thread pool with four threads
    ExecutorService execSvc = Executors.newFixedThreadPool( 8);
    * place six tasks in the work queue for the thread pool
    for( int i = 0; i < 6; i++ )
    execSvc.execute( new CountDown() );
         long a =System.currentTimeMillis();
    execSvc.execute( new databaseThread("00055","YTD","GROSS") );
    execSvc.execute( new databaseThread("00055","YTD","NET") );
    execSvc.execute( new databaseThread("00055","YTM","GROSS") );
    execSvc.execute( new databaseThread("00055","YTM","NET") );
    execSvc.execute( new databaseThread("00055","LY","GROSS") );
    execSvc.execute( new databaseThread("00055","LY","NET") );
    execSvc.execute( new databaseThread("00055","LLY","GROSS") );
    execSvc.execute( new databaseThread("00055","LLY","NET") );
         long b =System.currentTimeMillis();
         try{
         while(databaseThread.done!=8)
              Thread.sleep(1000);
         catch(Exception ex){}
    execSvc.shutdown();
    System.out.println("END TO END TIME TAKEN : "+(b-a));
    /////////////////////////////////////////////////////////// databaseThread.java
    import java.io.PrintWriter;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.io.PrintWriter;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.io.IOException;
    public class databaseThread implements Runnable
    protected int count = 8;
    * the following counter is incremented once
    * each time the class is instantiated, giving each
    * instance a unique number, which is printed in run()
    private static int taskCount = 0;
    private final int id = taskCount++;
    private String gpNum;
    private String time;
    private String domain;
    public static int i=0;
    public static int done=0;
    PrintWriter out = null;
    Connection connection = null;
    Statement statement;
    ResultSet rs;
    ResultSetMetaData rsmd;
         CallableStatement cStmt = null;
    public databaseThread(String gpNum, String time, String domain) {
    this.gpNum=gpNum;
    this.time=time;
    this.domain=domain;
    * print the id and the iteration count to the console, then
    * yield to another thread.
    public void run()
         try
         Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
         connection = DriverManager.getConnection("jdbc:sybase:Tds:XXXXXXXXXXX:XXXXXXX", "cp_dbo","cp_dbo");
         statement = connection.createStatement();
              cStmt=connection.prepareCall("{call XXXXXX ?,?,?)}");
              cStmt.setString(1,gpNum);
              cStmt.setString(2, time);
              cStmt.setString(3,domain);
              long a =System.currentTimeMillis();
              rs=cStmt.executeQuery();
              long b=System.currentTimeMillis();
              System.out.println(id+" Time taken by to execute Query : "+(b-a));
         //rsmd=rs.getMetaData();
              while(rs.next())
              Thread.yield();
         catch (ClassNotFoundException e) {
              System.out.println("Driver Error" );
              e.printStackTrace();
              } catch (SQLException e) {
              System.out.println("SQLException: " + e.getMessage());
    }

  • How can I get the variable with the value from Thread Run method?

    We want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
         public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    // I should get Inside the run method::: But I get only Inside
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";
    NB: if i write the variable in to a file I am able to read it from external method. This I dont want to do

    We want to access a variable from the run method of a
    Thread externally in a class or in a method. I presume you mean a member variable of the thread class and not a local variable inside the run() method.
    Even
    though I make the variable as public /public static, I
    could get the value till the end of the run method
    only. After that scope of the variable gets lost
    resulting to null value in the called method/class..
    I find it easier to implement the Runnable interface rather than extending a thread. This allows your class to extend another class (ie if you extend thread you can't extend something else, but if you implement Runnable you have the ability to inherit from something). Here's how I would write it:
    public class SampleSynchronisation
      public static void main(String[] args)
        SampleSynchronisation app = new SampleSynchronisation();
      public SampleSynchronisation()
        MyRunnable runner = new MyRunnable();
        new Thread(runner).start();
        // yield this thread so other thread gets a chance to start
        Thread.yield();
        System.out.println("runner's X = " + runner.getX());
      class MyRunnable implements Runnable
        String X = null;
        // this method called from the controlling thread
        public synchronized String getX()
          return X;
        public void run()
          System.out.println("Inside MyRunnable");
          X = "MyRunnable's data";
      } // end class MyRunnable
    } // end class SampleSynchronisation>
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run
    method "+sathr.x);
    // I should get Inside the run method::: But I get
    only Inside
    class sampleThread extends Thread
    public String x="Inside";
    public void run()
    x+="the run method";
    NB: if i write the variable in to a file I am able to
    read it from external method. This I dont want to do

  • What is it with yield() that I don't understand?

    The following code starts a thread that awaits a notification that never comes. However, I was expecting the Foo main thread to enter the running state again sometime after it yields and print the last line "main running again", but not so. The program hangs and never execute main's last print statement.
    class Task extends Thread {
    Foo foo;
    Task (Foo syncOnThis) {
        foo = syncOnThis;
        @Override
        public void run () {
        synchronized (foo) {
            System.out.println("task has the foo lock.");
            try {
                System.out.println("task about to release lock.");
                foo.wait();
            } catch (InterruptedException ie) {
                System.err.println("task was interrupted.");
            System.out.println("task was notified!");
    public class Foo {
        private synchronized void notifier() {
            notifyAll();
            System.out.println("foo notified all");
        public static void main(String[] args) {
            Foo foo = new Foo();
            Task alpha = new Task(foo);
            alpha.start();
        Thread.yield();
            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
                System.out.println("Foo's sleep interrupted");
                System.out.println("main thread running again");
    }My understanding of yield() is that it offers to demote the current thread to the runnable state in order to allow other threads - in this case Task - to enter the running state. But once Task calls wait(), it also retreats from the running state and this is where I expect the main thread to become running again.
    If I swap yield() with something like
            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
                System.out.println("Foo's sleep interrupted");
            }then it main does actually return to a running state and executes the last statement.
    what is it with yield() that I don't understand?

    krzn wrote:
    I see.Do also note that yield seldom is used these days. You most likely have a bug in your implementation or design if you think you need to call yield, or you are executing on a really old VM or on an odd system.
    (The first versions of the Solaris VM didn't use round robin so you had to release the execution to avoid starvation.)
    Kaj

  • 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)

Maybe you are looking for

  • Acrobat Pro 9 and Word 2007

    We've been using Pro9 in Office 2007 for about 12 months with no problems. Couple of weeks ago it hung up and after rebooting Acrobat had disappeared as a toolbar option. Excel is fine but not Word. Converting from scanner is also OK. Have uninstalle

  • Sorting differences between Oracle and SQL Server

    Hello All, This question is related to both Oracle and SQL Server I have a requirement where I want to compare 2 tables line by line. One table is in Oracle and other table is in SQL Server And suppose that both of the tables don't have a primary key

  • Web Services and CF

    Hello, I've just started using Coldfusion and I'm trying to invoke a Web Service: <cfinvoke webservice=" http://localhost/WebService1/Service1.asmx?wsdl" method="MyMethod" returnvariable="aString"> <cfinvokeargument name="arg1" value="1"/> <cfinvokea

  • Missing audio waveforms in GarageBand 10.0.1

    My GarageBand 10.0.1 does not create audio waveforms when I record. I can record and play back my voice, but I don't see any audio waveforms when I record or playback. I must be missing some really elemental step, but for the life of me I can't figur

  • SMS Picture messages won't save to my phone!

    Hi!  I am currently using my BlackBerry Curve 8520 on Virgin Mobile, and when my friends send me pictures of me when I click "Save Image" I click "save" and it says that it all saved well. But when I go to check it on the Media folder or put it as my