Program to demonstrate use of Thread in an applet to show multithreading in Java

This program makes the use of Runnable interface in Applet class to show the mutithreading in Java. The output of this program is that the string "MutiThreading In Java" will move from top to bottom with a delay of 50ms.

PROGRAM
import java.applet.Applet;
import java.awt.*;

public class AnimationUsingThread extends Applet implements Runnable {

 Image img;
 Thread t;
 Graphics g,g1;
 public void init() {
  img = createImage(400,400);
  g = getGraphics();
  g1 = img.getGraphics();
  t = new Thread(this);
  t.start();
 }
 
 public void run() {
  Font f = new Font("Cambria",Font.BOLD,16);
  g1.setFont(f);
  for(int i=1;i<=190;i+=3)
   drawme("MultiThreading In Java",20,i);
 }
 
 void drawme(String s,int x,int y) {
  g1.setColor(Color.black);
  g1.fillRect(0,0,400,400);
  g1.setColor(Color.white);
  g1.drawString(s,x,y);
  g.drawImage(img,0,0,this);
  try
  {
   Thread.sleep(50);
  }catch(Exception ee){ }
 }
}

/* <applet code="AnimationUsingThread.class" width="200" height="200">
   </applet> */

OUTPUT

C:\>javac AnimationUsingThread.java
C:\>appletviewer AnimationUsingThread.java


Comments

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.

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

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.