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 : 7
One : 8
Two : 8
One : 9
Two : 9
One : 10
Two : 10

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative