Results 1 to 5 of 5

Thread: Threads in Java

  1. #1
    Join Date
    Apr 2008
    Posts
    513

    Threads in Java

    1. General Explanation

    1.1. What is a Thread:

    To avoid ambiguity, it is important to note that a thread is not a process. Indeed, the process live in virtual isolation, while Threads are treatments that live together within a single process. Threads share the same memory as opposed to process. A Thread is a bit of code that can run in parallel to other treatments. They are useful in many cases and sometimes even necessary. They serve many thing such as:

    - Doing treatments in the background, in the case of syntax highlighting editors.
    - Run multiple instances of the same code to speed up processing for long treatments not using the same resources.
    - Personal contact in order to multiple clients such as HTTP servers or IM.
    - Solve some problems related to mode of Swing.

    The threads do not run simultaneously but they share time between them. Therefore it is important for a Thread to always leave a chance for others to run. The diagram below illustrates the execution time and latency of threads.



    1.2 Life Cycle of a Thread:

    The Thread may have 4 different states, but only 2 can be tested.



    1.2.1. New State

    This is the initial state after instantiation of Thread. At this stage, the thread is operational but it is not yet active. A thread is that state after instantiation.

    1.2.2. State executable

    A thread is executable in a state from the moment it was launched by the start () method and the rest as it is, but not out of the run () method. Once the system can, it will give execution time to your Thread.

    1.2.3. State Waiting

    A waiting thread is a thread that does no treatment and does not consume any CPU power. There are several ways to a waiting thread.

    For example:
    Call the method Thread.sleep (time in milliseconds). Call the method wait (); Accessing a resource locking (Flux, access database, etc ...). Accessing an instance on which a lock was placed. Call the method suspend () thread. A waiting thread is considered executable.

    1.2.4. State Death

    A thread in a state death is a thread that is out of the run () method in a natural way, either so suddenly that it can be ab uncaught exception.

  2. #2
    Join Date
    Apr 2008
    Posts
    513

    Re: Threads in Java

    1.3. The interface Runnable:

    Before discussing the Thread class, we will study the Runnable interface in package java.lang. The Runnable interface offers us a unique method, the run method whose signature is as follows: Our treatment should be in this method. He can not take any parameter and can not return value.

    Code:
    Signature of the run
    Public void run ();
    If we need parameters, we pass to the builder who will store it in instance variable. An accessor can be set up to retrieve a value at the end of treatment.

    1.4. The Thread class:

    The Thread class of the java.lang package is one that must necessarily be derived for a class, so that it can be considered as a Thread and therefore executable in parallel. This concrete class implements the Runnable interface. The code you want to see implemented during activation should be placed in the run () method seen previously.

    The main constructors of the Thread class are:

    Code:
    Public Thread ();
    Public Thread (Runnable runnable);
    Starting a Thread must be done by the start () method.

    Code:
    ExThread t = new ExThread ();
    t.start ();
    A simple implementation of Thread.

    Code:
    Public class ExThread extends Thread {
      Public void run () {
        // Do something
      }
    }
    Code:
    Public class ExThread extends Thread {
      private String s;
      
      Public ExThread (String s) {
        this. s = s;
      }
      Public void run () {
        / / Do something with s
      }
    }
    1.5. A Thread Example:

    In the first concrete example, we learn to write a simple thread to initialize and run. To demonstrate that the thread is active at the same time as the main class, it will make postings on the console.

    Code:
    Public class ExThread extends Thread {
      Public void run {} {
        long str = System.currentTimeMillis {};
        / / Loop until the lifetime of the Thread is <5 seconds
        while{System.currentTimeMillis {} <{str + {1000 * 5}}} {
          / / Processing
          System.out.println {"Displayed by the thread"};
          try {
            / / Pause
            Thread.sleep {500};
          }
          catch {InterruptedException ex} {}
        }
      }
    }
    Code:
    Public class Main {
      Public Main {} {
        / / Create an instance of Thread
        ExThread thr = new ExThread {};
        / / Enable Thread
        thr.Start {};
        / / While the thr is alive ...
        while{Thread.isAlive {}} {
          / / Do processing ...
          System.out.println {"Line displayed by the hand"};
          try {
            / / And take a break
            Thread.sleep {800};
          }
          catch {InterruptedException ex} {}
        }
      }
      
      Public static void main {String[] Args} {
        new Main {};
      }
    
    }

  3. #3
    Join Date
    Apr 2008
    Posts
    513

    Re: Threads in Java

    2. Synchronizing Threads

    It is not uncommon to have to work a set of threads simultaneously. As long as each thread only manipulate data of its own, it poses no concern. The trouble will arrive soon as the data manipulation are common. The data are risking their integrity if two threads are found to handle simultaneously.To illustrate this, let's take the example of communicating vessels. Two vessels initially filled with the same amount. At each iteration, we will remove X one to add to another. We will check to ensure that the sum of the two corresponds to the original volume.

    Code:
    Public class vtest {
        private static Final int qnt_ini = 200;
        private static Final int thr_mx = 2;
        
        private static int iter = 0;
        
        private int[] = (qnt_ini vase / 2 qnt_ini / 2);
    
        Public vtest () {
            for( int i = 0; i <thr_mx; i + +)
                new ThreadTransfert (). Start ();
        }
        Public static void main (String[] Args) {
            new vtest ();
        }
        
        Public int transfer (int qty) {
            
            System.out.println ("-("+ + qty") vessel 1");
            vase [0] -= qty;
            System.out.println ("+("+ + qty") vessel 2");
            vessel [1] + = qty;
            iter + +;
            if(Iteration% 1000 == 0)
                System.out.println ("" Iteration + + "Iterations.");
            return vase [0] + pot [1];
        }
        
        Public class ThreadTransfert extends Thread {
            Random r = new Random ();
            int qnty;
            Public void run () {
                while(! IsInterrupted ()) {
                    qnty = r.nextInt (11) -6;
                    vase [0] -= qty;
                    vessel [1] + = qnty;
                    if(Transfer (qnty)! = qnt_ini) {
                        System.out.println ("Total qnty invalid iter" + Iteration);
                        System.exit (-1);
                    }
                    
                    try {
                        Thread.sleep (10);
                    } catch (InterruptedException e) ()
                }
            }
            
        }
    }
    If you run this code, you may well have provoked a violent before the 500 iterations. Playing with the value of thr_mx, results may vary knowing that with a value of 1, there is no risk of error. Plus you'll have more threads and treatment will be, the more chance you have to break the integrity of your data. To overcome this problem, we simply declare the method synchronized transfer like this:

    Code:
    public synchronized int transfer (int qty) {
      ...
    }
    The synchronized keyword indicates that a single thread and a little get together with this method. Thus, the data manipulated not unlikely to be altered. Attention misuse of synchronized methods can substantially reduce the performance of your applications.

  4. #4
    Join Date
    Apr 2008
    Posts
    513

    Re: Threads in Java

    3. Swing and Thread

    Swing uses a battery of events called EventQueue. The mechanism is very simple once you understood its operation, many problems of Swing find an explanation, therefore, a solution.

    Some reminders about the specification of the virtual machine:

    - Events must be popped in the same order.
    - The events should be dispatched at the same time.

    We will illustrate this part of the specification of the JVM using two simple programs, one written in a so-called "natural" and the other using a Thread. To do this, pick up the recurrent problem of displaying a progress bar during a long treatment. Our treatment here will be represented by a class by 100 iterations unnecessary but made a break of 100 ms.

    Code:
    Public class LongAction {
    
        Public void trtlng (JProgressBar pbr) {
           
            pbr.setMinimum (0);
            pbr.setMaximum (99);
            pbr.setValue (0);
            
            / / Treatment
            for( int i = 0; i <100; i + +) {
                System.out.println (".");
                pbr.setValue (i);
                try {
                    / / Pause to simulate a treatment
                    Thread.sleep (100);
                } catch (InterruptedException e) ()
            }
            System.out.println ("") ;
        }
    }
    Code:
    Public class testtrtlng extends JFrame {
      JProgressBar jpbr = new JProgressBar ();
      GridLayout lyot = new GridLayout (2,1);
      JButton jbtt = new JButton ("Start processing");
    
      Public testtrtlng () {
        / / Build the test window
        Container conpn = getContentPane ();
        conpn.setLayout (lyot);
        conpn.add (jpbr);
        conpn.add (jbtt);
        setTitle ("Test progressBar");
       
        jbtt.addActionListener {
          new ActionListener () {
            Public void actPerformed (ActionEvent e) {
              / / Instantiate and start treatment
              LongAction act = new LongAction ();
              act.trtlng (jpbr);
           }
          }
        };
            
        / / Display window
        pack ();
        setVisible (true);
    }
      
      Public static void main (String[] Args){
        new testtrtlng ();
      }
    }
    If you run this application you will see a number of things.

    - The progress bar does not advance.
    - The console displays many items that indicates that processing takes place.
    - If you enlarge the window for treatment, it does not refresh.
    - At the end of treatment, the progress bar displays 100% and the window is redrawn correctly.

    In our example, the first event is explicitly popped the button. As long as the button code is not completed, no other event will be popped. So, at each change of status of the progress bar, the event related to cooling of the component graphic is stacked and waiting for the button code is completed to be popped in turn. We can therefore say that our treatment of piles 100 events refreshments. If in addition you have resized the window, it does the same event waiting in the stack of events. To resolve this problem, simply that the event button is no longer blocking. For this, we use a thread to make the earliest possible hand in the EventQueue Swing. It is unnecessary to change all your treatments and place them in threads, we create Thread dynamically so, no need to changes are the code of your method.

    Here is the code of the modified button Listener.

    Code:
    jbtt.addActionListener {
      new ActionListener () {
        Public void acper (ActionEvent e) {
          / / Create a thread of execution
          Thread t = new Thread () {
            Public void run () {
              / / Instantiate and start treatment
              LongAction act = new LongAction ();
              act.trtlng (jbtv);
            }
          };
          t.start ();
        }
      }
    };

  5. #5
    Join Date
    Apr 2008
    Posts
    513

    Re: Threads in Java

    4. Conclusion

    The scheduling of threads is inherently complex, but requires a good understanding. Starting in the developing multi-threading without understanding the mechanisms of these is a significant risk. In the example on the timing, try removing the displays to the console that I deliberately inserted between addition and subtraction. It's a safe bet that you will not desync for several thousands of iterations or no synchronization at all. But for that little something disrupts the launch of the N threads and that these calls are different in time. If you would like to add some additional information to this then feel free to do it.

Similar Threads

  1. What would be a limit for threads per day?
    By Cauvery in forum Technology & Internet
    Replies: 7
    Last Post: 21-07-2011, 11:47 PM
  2. Problems with multiple threads and GUI refresh in Java
    By Devabrata in forum Software Development
    Replies: 3
    Last Post: 30-07-2010, 01:24 AM
  3. Threads in JavaFX
    By Rily in forum Software Development
    Replies: 3
    Last Post: 15-07-2010, 04:02 PM
  4. threads concept in java
    By vijji191 in forum Software Development
    Replies: 2
    Last Post: 30-11-2009, 03:44 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,944,405.67907 seconds with 17 queries