Showing posts with label Java Threads. Show all posts
Showing posts with label Java Threads. Show all posts

Monday, January 2, 2012

Set Thread Name

package org.best.example;

    /*
            Set Thread Name Example
            This Java example shows how to set name of thread using setName method
            of Thread class.
    */
    
    public class SetThreadNameExample {
    
            public static void main(String[] args) {
                  
                    //get currently running thread object
                    Thread currentThread = Thread.currentThread();
                    System.out.println(currentThread);
                  
                    /*
                     * To set name of thread, use
                     * void setName(String threadName) method of
                     * Thread class.
                     */
                  
                    currentThread.setName("Set Thread Name Example");
                  
                    /*
                     * To get the name of thread use,
                     * String getName() method of Thread class.
                     */
                    System.out.println("Thread Name : "+ currentThread.getName());
            }
    }
    
    /*
    Output of the example would be
    Thread[main,5,main]
    Thread Name : Set Thread Name Example
    */

Sunday, January 1, 2012

Pause Thread Using Sleep Method

package org.best.example;

    /*
            Pause Thread Using Sleep Method Example
            This Java example shows how to pause currently running thread using
            sleep method of Java Thread class.
    */
    
    public class PauseThreadUsingSleep {
    
            public static void main(String[] args) {
                  
                    /*
                     * To pause execution of a thread, use
                     * void sleep(int milliseconds) method of Thread class.
                     *
                     * This is a static method and causes the suspension of the thread
                     * for specified period of time.
                     *
                     * Please note that, this method may throw InterruptedException.
                     */
                  
                    System.out.println("Print number after pausing for 1000 milliseconds");
                    try{
                          
                            for(int i=0; i< 5; i++){
                                  
                                    System.out.println(i);
                                  
                                    /*
                                     * This thread will pause for 1000 milliseconds after
                                     * printing each number.
                                     */
                                    Thread.sleep(1000);
                            }
                    }
                    catch(InterruptedException ie){
                            System.out.println("Thread interrupted !" + ie);
                    }
                  
            }
    }
    
    /*
    Output of this example would be
    
    Print number after pausing for 1000 milliseconds
    0
    1
    2
    3
    4
    */

Saturday, December 31, 2011

Get Current Thread

 package org.best.example;

   /*
            Get Current Thread Example
            This Java example shows how to get reference of current thread using
            currentThread method of Java Thread class.
    */
   
    public class GetCurrentThreadExample {
   
            public static void main(String[] args) {
                 
                    /*
                     * To get the reference of currently running thread, use
                     * Thread currentThread() method of Thread class.
                     *
                     * This is a static method.
                     */
                 
                    Thread currentThread = Thread.currentThread();
                    System.out.println(currentThread);
                 
            }
    }
   
    /*
    Output of the example would be
    Thread[main,5,main]
    */

Friday, December 30, 2011

Create New Thread Using Runnable

package org.best.example;

    /*
            Create New Thread Using Runnable Example
            This Java example shows how to create a new thread by implementing
            Java Runnable interface.
    */
    
    /*
     * To create a thread using Runnable, a class must implement
     * Java Runnable interface.
     */
    public class CreateThreadRunnableExample implements Runnable{
    
            /*
             * A class must implement run method to implement Runnable
             * interface. Signature of the run method is,
             *
             * public void run()
             *
             * Code written inside run method will constite a new thread.
             * New thread will end when run method returns.
             */
            public void run(){
                  
                    for(int i=0; i < 5; i++){
                            System.out.println("Child Thread : " + i);
                          
                            try{
                                    Thread.sleep(50);
                            }
                            catch(InterruptedException ie){
                                    System.out.println("Child thread interrupted! " + ie);
                            }
                    }
                  
                    System.out.println("Child thread finished!");
            }
          
            public static void main(String[] args) {
                  
                    /*
                     * To create new thread, use
                     * Thread(Runnable thread, String threadName)
                     * constructor.
                     *
                     */
                  
                    Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
                  
                    /*
                     * To start a particular thread, use
                     * void start() method of Thread class.
                     *
                     * Please note that, after creation of a thread it will not start
                     * running until we call start method.
                     */
                  
                    t.start();
                  
                    for(int i=0; i < 5; i++){
                          
                            System.out.println("Main thread : " + i);
                          
                            try{
                                    Thread.sleep(100);
                            }
                            catch(InterruptedException ie){
                                    System.out.println("Child thread interrupted! " + ie);
                            }
                    }
                    System.out.println("Main thread finished!");
            }
    }
    
    /*
    Typical output of this thread example would be
    
    Main thread : 0
    Child Thread : 0
    Child Thread : 1
    Main thread : 1
    Main thread : 2
    Child Thread : 2
    Child Thread : 3
    Main thread : 3
    Main thread : 4
    Child Thread : 4
    Child thread finished!
    Main thread finished!
    
    */

Thursday, August 25, 2011

Stop watch programme using Java Threads

package org.best.example;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Stopwatch extends JFrame implements ActionListener, Runnable
    {
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
         {
         public void run()
             {
             displayElapsedTime(System.currentTimeMillis() - Stopwatch.this.startTime);
         }
     };
     public void actionPerformed(ActionEvent ae)
         {
         if(isRunning)
             {
             long elapsed= System.currentTimeMillis() - startTime;
             isRunning= false;
             try
                 {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
             {
             startTime= System.currentTimeMillis();
             isRunning= true;
             updater= new Thread(this);
             updater.start();
         }
     }
     private void displayElapsedTime(long elapsedTime)
         {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
     }
     public void run()
         {
         try
             {
             while(isRunning)
                 {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
             {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
     public static void main(String[] arg)
         {
         new Stopwatch().addWindowListener(new WindowAdapter()
             {
             public void windowClosing(WindowEvent e)
                 {
                 System.exit(0);
             }
         });
     }
}

Wednesday, August 24, 2011

Demonstrating the runnable interface

package org.best.example;
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class RandomCharacters extends JApplet implements Runnable, ActionListener
 {
     private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     private JLabel outputs[];
     private JCheckBox checkboxes[];
     private final static int SIZE = 3;

     private Thread threads[];
     private boolean suspended[];

     public void init()
     {
         outputs = new JLabel[ SIZE ];
         checkboxes = new JCheckBox[ SIZE ];
         threads = new Thread[ SIZE ];
         suspended = new boolean[ SIZE ];

         Container c = getContentPane();
         c.setLayout( new GridLayout( SIZE, 2, 5, 5 ) );

         for ( int i = 0; i < SIZE; i++ )
         {
             outputs[ i ] = new JLabel();
             outputs[ i ].setBackground( Color.green );
             outputs[ i ].setOpaque( true );
             c.add( outputs[ i ] );

             checkboxes[ i ] = new JCheckBox( "Suspended" );
             checkboxes[ i ].addActionListener( this );
             c.add( checkboxes[ i ] );
         }
    }

     public void start()
     {
         // create threads and start every time start is called
         for ( int i = 0; i < threads.length; i++ )
         {
             threads[ i ] = new Thread( this, "Thread " + (i + 1) );
             threads[ i ].start();
         }
     }

     public void run()
     {
         Thread currentThread = Thread.currentThread();
         int index = getIndex( currentThread );
         char displayChar;

         while ( threads[ index ] == currentThread )
         {
             // sleep from 0 to 1 second
             try
             {
                 Thread.sleep( (int) ( Math.random() * 1000 ) );

                 synchronized( this )
                 {
                     while ( suspended[ index ] && threads[ index ] == currentThread )
                     wait();
                 }
             }
             catch ( InterruptedException e )
             {
                 System.err.println( "sleep interrupted" );
             }

             displayChar = alphabet.charAt( (int) ( Math.random() * 26 ) );
             outputs[ index ].setText( currentThread.getName() +
             ": " + displayChar );
         }

         System.err.println( currentThread.getName() + " terminating" );
     }

     private int getIndex( Thread current )
     {
         for ( int i = 0; i < threads.length; i++ )
             if ( current == threads[ i ] )
                 return i;

         return -1;
     }

     public synchronized void stop()
     {
         // stop threads every time stop is called
         // as the user browses another Web page
         for ( int i = 0; i < threads.length; i++ )
             threads[ i ] = null;

         notifyAll();
     }

     public synchronized void actionPerformed( ActionEvent e )
     {
         for ( int i = 0; i < checkboxes.length; i++ )
         {
             if ( e.getSource() == checkboxes[ i ] )
             {
                 suspended[ i ] = !suspended[ i ];

                 outputs[ i ].setBackground( !suspended[ i ] ? Color.green : Color.red );

                 if ( !suspended[ i ] )
                 notify();

                 return;
             }
         }
     }
 }