Posts

Showing posts with the label Multithreading

Program to demonstrate thread synchronization

This program demonstrates the use of thread synchronization. We have serialized the access to  display( )  method. To restrict the access to display( ) method to only one thread at a time we need to preceed  display( ) 's definition with the keyword  synchronized  as shown below. PROGRAM class Sync { void display(String s) { System.out.print("[" + s); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Exception"); } System.out.println("]"); } } class SyncTest extends Thread { String z = ""; Sync x; Thread t; public SyncTest(Sync y, String s) { x = y; z = s; t = new Thread(this); t.start(); } public void run() { x.display(z); } } public class SynchronizationDemo { public static void main(String[] args) { Sync s = new Sync(); SyncTest s1 = new SyncTest(s, "Hello"); SyncTest s2 = new SyncTest(s, "Rohit"); SyncTest s3 = new SyncTest(...

Program to input a string and print each character from that separately on screen with a delay of 100ms after each character

This program will print each character from a given string with a delay of 100ms. PROGRAM import java.util.Scanner; public class PrintCharWithDelay { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter the string :: "); String str = s.nextLine(); for(int i=0; i<str.length(); i++) { System.out.println(str.charAt(i)); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } OUTPUT C:\>javac PrintCharWithDelay.java C:\>java PrintCharWithDelay Enter the string :: Rahul R a h u l

Write a program to create a thread to print all even nos. from 1 to 50 with delay to 100 after each number

This program will print all even numbers between 1 to 50 with 100ms delay after each number. PROGRAM class EvenNum1To50 extends Thread { public void run() { for(int i=1; i<=50; i++) { if(i%2 == 0) System.out.println("Even Thread: "+i); try { Thread.sleep(100); } catch (InterruptedException e) { } } } } public class EvenThreadWithDelay { public static void main(String[] args) { new EvenNum1To50().start(); } } OUTPUT C:\>javac EvenThreadWithDelay.java C:\>java EvenThreadWithDelay Even Thread: 2 Even Thread: 4 Even Thread: 6 Even Thread: 8 Even Thread: 10 Even Thread: 12 Even Thread: 14 Even Thread: 16 Even Thread: 18 Even Thread: 20 Even Thread: 22 Even Thread: 24 Even Thread: 26 Even Thread: 28 Even Thread: 30 Even Thread: 32 Even Thread: 34 Even Thread: 36 Even Thread: 38 Even Thread: 40 Even Thread: 42 Even Thread: 44 Even Thread: 46 Even Thread: 48 Even Thread: 50

Program to create two threads, which alternately displays numbers from 1 to 10. Each thread sleeps for 1 second before displaying next number

This is a simple program which uses  sleep(long millisec)  method of Thread class. It causes to pause the execution of thread for specified number of milliseconds. The output of the program may vary. PROGRAM class One extends Thread { public void run() { for(int i=1; i<=10; i++) { System.out.println("One : "+i); try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } } class Two extends Thread { public void run() { for(int i=1; i<=10; i++) { System.out.println("Two : "+i); try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } } public class AlternateTwoThreads { public static void main(String[] args) { One t1 = new One(); Two t2 = new Two(); t1.start(); t2.start(); } } OUTPUT C:\javac AlternateTwoThreads.java C:\java AlternateTwoThreads One : 1 Two : 1 Two : 2 One : 2 One : 3 Two : 3 One : 4 Two : 4 One : 5 Two : 5 One : 6 Two : 6 One : 7 Two : ...

Program to create two threads, one for Prime number and other for Non-prime number

This is a simple program which prints prime and non-prime numbers from 1 to 10.   PROGRAM class Prime extends Thread { public void run() { for(int i=1; i<=10; i++) { if(i==2 || i==3 || i==5 || i==7) System.out.println("Prime no. : " + i); } } } class NonPrime extends Thread { public void run() { for(int i=1; i<=10; i++) { if(i==4 || i==6 || i==8 || i==9 || i==10) System.out.println("Non-Prime no. : " + i); } } } public class PrimeNotPrimeThread { public static void main(String[] args) { new Prime().start(); new NonPrime().start(); } } OUTPUT C:\>javac PrimeNotPrimeThread.java C:\>java PrimeNotPrimeThread Prime no. : 2 Prime no. : 3 Prime no. : 5 Prime no. : 7 Non-Prime no. : 4 Non-Prime no. : 6 Non-Prime no. : 8 Non-Prime no. : 9 Non-Prime no. : 10

Program to create two threads, one will print numbers in original order and other in reverse order from 1 to 50

To accomplish this task we have created two thread classes  Original  and  Reverse  which prints numbers from 1 to 50 in original and reverse order respectively. PROGRAM class Original extends Thread { public void run() { for(int i=1; i<=50; i++) { System.out.println("Original Order Thread : " + i); } } } class Reverse extends Thread { public void run() { for(int i=50; i>0; i--) { System.out.println("Reverse Order Thread : " + i); } } } public class OriginalReverseThread { public static void main(String[] args) { new Original().start(); new Reverse().start(); } } OUTPUT C:\>javac OriginalReverseThread.java C:\>java OriginalReverseThread Original Order Thread : 1 Original Order Thread : 2 Original Order Thread : 3 Original Order Thread : 4 Original Order Thread : 5 Original Order Thread : 6 Original Order Thread : 7 Original Order Thread : 8 Original Order Thread : 9 Original Order Thread : 10 Original O...

Program to create two threads, one for even numbers and other for odd numbers

To accomplish this task we have created two thread classes  Even  and  Odd  which prints even and odd numbers from 1 to 10 respectively. For checking number is odd or even we have used mod (%) operator if no%2 = 0 then it is even number otherwise it is odd number. PROGRAM class Even extends Thread { public void run() { for(int i=1; i<=10; i++) { if(i % 2 == 0) System.out.println("Even : " + i); } } } class Odd extends Thread { public void run() { for(int i=1; i>=10; i++) { if(i % 2 != 0) System.out.println("Odd : " + i); } } } public class EvenOddThreadSimple { public static void main(String[] args) { new Even().start(); new Odd().start(); } } OUTPUT C:\>javac EvenOddThreadSimple.java C:\>java EvenOddThreadSimple Even : 2 Even : 4 Even : 6 Even : 8 Even : 10 Odd : 1 Odd : 3 Odd : 5 Odd : 7 Odd : 9

Program for creating three threads

In this program, we have created three threads  X, Y  and  Z . Each of them will print message for 3 times as shown in output. PROGRAM class X extends Thread { public void run() { for(int i=1;i<=3;i++) { System.out.println("From Thread X : "+i); } System.out.println("Exit Thread X"); } } class Y extends Thread { public void run() { for(int i=1;i<=3;i++) { System.out.println("From Thread Y : "+i); } System.out.println("Exit Thread Y"); } } class Z extends Thread { public void run() { for(int i=1;i<=3;i++) { System.out.println("From Thread Z : "+i); } System.out.println("Exit Thread Z"); } } public class ThreeThreads { public static void main(String[] args) { new X().start(); new Y().start(); new Z().start(); } } OUTPUT C:\>javac ThreeThreads.java C:\>java ThreeThreads From Thread X : 1 From Thread X : 2 From Thread X : 3 Exit Thread X Fr...

Write a program to define two threads one will print 1 to 10 numbers whereas other will print 11 to 20 numbers

In this program, we have to create two threads, one will print numbers from 1 to 10 and other will print numbers from 11 to 20. The  OneTo10  thread will print 1 to 10 numbers and  ElevenTo20  thread will print 11 to 20 numbers. The  start( )  method starts the execution of thread. PROGRAM class OneTo10 extends Thread { public void run() { for(int i=1; i<=10; i++) { System.out.println("OneTo10 : " + i); } } } class ElevenTo20 extends Thread { public void run() { for(int i=11; i<=20; i++) { System.out.println("ElevenTo20 : " + i); } } } public class OneToTenThread { public static void main(String[] args) { new OneTo10().start(); new ElevenTo20().start(); } } OUTPUT C:\>javac OneToTenThread.java C:\>java OneToTenThread OneTo10 : 1 OneTo10 : 2 OneTo10 : 3 OneTo10 : 4 OneTo10 : 5 OneTo10 : 6 OneTo10 : 7 OneTo10 : 8 OneTo10 : 9 OneTo10 : 10 ElevenTo20 : 11 ElevenTo20 : 12 ElevenTo20 : 13 ElevenTo20 : 14 E...

Program to create two threads, one thread will print numbers in ascending order where as second thread will print numbers in descending order between 1 to 15

In this program, we have created two threads, one thread will print numbers from 1 to 15 in ascending order and other thread will print numbers in descending order. The logic to do the same is shown in program. Note that the output of thread programs may vary. PROGRAM class Ascending extends Thread { public void run() { for(int i=1; i<=15;i++) { System.out.println("Ascending Thread : " + i); } } } class Descending extends Thread { public void run() { for(int i=15; i>0;i--) { System.out.println("Descending Thread : " + i); } } } public class AscendingDescendingThread { public static void main(String[] args) { new Ascending().start(); new Descending().start(); } } OUTPUT C:\javac AscendingDescendingThread.java C:\java AscendingDescendingThread Ascending Thread : 1 Ascending Thread : 2 Ascending Thread : 3 Ascending Thread : 4 Ascending Thread : 5 Ascending Thread : 6 Ascending Thread : 7 Ascending Thread : 8 Asc...

Program for showing Thread class methods.

The below program shows some of the method of  Thread  class. The minimum, normal and maximum priority of thread are 1, 5 and 10 respectively. Method with its explanation are given below: static Thread currentThread( ) :  Returns a reference to the currently executing thread object. long getId( ) :  Returns the identifier of Thread. String getName( ) :  Returns thread's name. int getPriority( ) :  Returns thread's priority. Thread.State getState( ) :  Returns the state of thread. ThreadGroup getThreadGroup( ) :  Returns the thread group to which thread belongs. boolean isAlive( ) :  Tests if the thread is alive. boolean isDaemon( ) :  Tests if the thread is a daemon thread. void join(long millis) :  Waits at most millis milliseconds for the thread to die. void setDaemon(boolean on) :  Marks thread as either a daemon thread or a user thread. void setName(String name) :  Changes the name of thread specified by ...

Program for pausing thread.

This program demonstrates you how to pause the execution of thread. The  sleep(long millis)  method of Thread class causes the currently executing thread to sleep for the specified number of milliseconds. This method throws an  InterruptedException  exception. The output of this program is first it print "Hello" after 1 second "from" will print and then "Java" will print after 1 second. PROGRAM public class PausingThread { public static void main(String[] args) { try{ System.out.println("Hello"); Thread.sleep(1000); System.out.println("from"); Thread.sleep(1000); System.out.println("Java."); Thread.sleep(1000); } catch (InterruptedException e){ } } } OUTPUT C:\>javac PausingThread.java C:\>java PausingThread Hello from Java.

Program for Naming a Thread

This program demonstrates you how to change the thread name. The  setName(String)  method of Thread class is used to set the name of thread. PROGRAM public class NamingThread { public static void main(String[] args) { Thread thread = Thread.currentThread(); System.out.println("Main thread's original name is : "+thread.getName()); thread.setName("The Main Thread"); System.out.println("Main thread's new name is : "+thread.getName()); } } OUTPUT C:\>javac NamingThread.java C:\>java NamingThread Main thread's original name is : main Main thread's new name is : The Main Thread

Program to getting the main thread

This is a simple program in which we are getting the reference of currently executing thread object. The  currentThread( )  method returns the reference of currently executing thread. The  getName( )  returns the thread name. PROGRAM class GettingMainThread { public static void main (String[] args) { Thread thread = Thread.currentThread(); System.out.println("Main thread is named : "+thread.getName()); } } OUTPUT C:\>javac GettingMainThread.java C:\>java GettingMainThread Main thread is named : main

Program to create two threads such that one thread displays the message "How do you do ?" and the other thread displays the message "Fine, Thank you!"

In this program, we have created two threads, first thread will print "How do you do?" and other thread will print "Fine, Thank you!". Here the start( ) method is called in class's constructor. Note that the output of thread programs is not same all the time it may vary. The start( ) method causes the thread to begin execution, the JVM calls the run( ) method of the thread. PROGRAM class MyThread extends Thread { String msg; public MyThread(String msg) { this.msg = msg; start(); } public void run() { System.out.println(msg); } public static void main(String[] args) { MyThread t1 = new MyThread("How do you do ?"); MyThread t2 = new MyThread("Fine, Thank you!"); } } OUTPUT C:\>javac MyThread.java C:\>java MyThread How do you do ? Fine, Thank you!

Program for implementing Runnable interface

There are two ways to create a thread: By extending  Thread  class By implementing  Runnable  interface. This program demonstrates you how to use the second mechanism for creating threads by implementing  Runnable  interface. The steps for creating a thread by using the second mechanism are: Create a subclass that implements the interface  Runnable  and override  run( )  method: class MyThread implements Runnable { // Overrride run( ) method with "public" access specifier public void run( ) { // Thread body of execution } } Create an object MyThread t1 = new MyThread( ); Creating Thread object Thread t = new Thread( t1 ); Start Execution of created thread by calling  start( )  method: t.start( ); PROGRAM class ImpementingRunnable implements Runnable { @Override public void run() { System.out.println("This thread is running ... "); } public static void main(String[] args) { Thread t ...

Program for extending Thread class

Java is a  multi-threaded programming language  which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. A  thread  is a dispatchable unit of work. Threads are light-weight processes within a process. A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. There are two ways to create a thread: By extending  Thread  class By implementing  Runnable  interface. In this program, we will see how to use the first method (extending  Thread  class). The steps for creating a thread by extending Thread class are given below: Create a subclass by extending the  Thread  class and override the run( ) method: class MyThread extends T...