KEMBAR78
Java Multithreading Practical Guide | PDF | Thread (Computing) | Computing Platforms
0% found this document useful (0 votes)
1K views12 pages

Java Multithreading Practical Guide

This document contains solutions to 7 questions on multithreading programs in Java. The programs include: 1. Displaying vowels from a string using multiple threads. 2. Simulating a traffic signal using threads that change the light color every 5 seconds. 3. Drawing a temple flag on an applet container using threads. 4. Simulating a car race with two cars moving across the frame in different threads. 5. Blinking text on a frame using threads. 6. Moving text across a frame in different directions using threads. 7. Simulating a bouncing ball that changes color with each bounce using threads.

Uploaded by

priyanka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views12 pages

Java Multithreading Practical Guide

This document contains solutions to 7 questions on multithreading programs in Java. The programs include: 1. Displaying vowels from a string using multiple threads. 2. Simulating a traffic signal using threads that change the light color every 5 seconds. 3. Drawing a temple flag on an applet container using threads. 4. Simulating a car race with two cars moving across the frame in different threads. 5. Blinking text on a frame using threads. 6. Moving text across a frame in different directions using threads. 7. Simulating a bouncing ball that changes color with each bounce using threads.

Uploaded by

priyanka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

TYBCA Practical On Multithreading (File2)

Q1. Write a multithreading program in Java to display all the vowels from a given string.
(Use Thread class) Slip 2

Solution:-

import java.io.*;

class VowelsThread extends Thread{


private String s;

public VowelsThread(String str){


s = str;
}

public void run(){


for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' ||
c=='A' || c=='E' || c=='I' || c=='O' || c=='U')
System.out.println(i+":"+c);

try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){}
}
}
}

class VowelsThreadTest{
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.print("Enter string:");
String s = br.readLine();

VowelsThread t = new VowelsThread(s);


t.start();
}
}

Q2. Write a Java program to simulate traffic signal using multithreading. Slip3

Solution:-

import java.awt.*;
import java.awt.event.*;

class TrafficSignal extends Frame{


private int f;
private MyThread t;
TYBCA Practical On Multithreading (File2)

public TrafficSignal(){
t = new MyThread();
t.start();

setTitle("Traffic Signal");
setSize(150,500);
setVisible(true);
setBackground(Color.BLACK);
}

public void paint(Graphics g){


super.paint(g);
int w = 100;
int h = 100;

switch(f){
case 0:
g.setColor(Color.RED);
g.fillOval(70,200,w,h);
g.setColor(Color.WHITE);
g.fillOval(70,h+200,w,h);
g.fillOval(70,2*h+200,w,h);
break;
case 1:
g.setColor(Color.YELLOW);
g.fillOval(70,h+200,w,h);
g.setColor(Color.WHITE);
g.fillOval(70,200,w,h);
g.fillOval(70,2*h+200,w,h);
break;
case 2:
g.setColor(Color.GREEN);
g.fillOval(70,2*h+200,w,h);
g.setColor(Color.WHITE);
g.fillOval(70,200,w,h);
g.fillOval(70,h+200,w,h);
break;
}
}

class MyThread extends Thread{


public void run(){
while(true){
f=(f+1)%3;
repaint();
try{
Thread.sleep(5000);
}
catch(Exception e){}
}
}
}

public static void main(String args[]){


new TrafficSignal();
}
}
TYBCA Practical On Multithreading (File2)

Q3. Write a Multi-threading program in Java using Runnable interface to draw temple flag
on an applet container. Slip5
Solution:-
import java.awt.*;
import java.applet.*;

public class TempleApplet extends Applet implements Runnable{


private int flag;

public void init(){


Thread t = new Thread(this);
t.start();
}

public void paint(Graphics g){


switch(flag){
case 11:
g.drawLine(45,150,65,150);
case 10:
g.drawLine(65,200,65,150);
case 9:
g.drawLine(45,200,45,150);
case 8:
g.drawLine(75,10,55,30);
case 7:
g.drawLine(55,10,75,10);
case 6:
g.drawLine(55,50,55,10);
case 5:
g.drawLine(110,100,55,50);
case 4:
g.drawLine(10,100,55,50);
case 3:
g.drawLine(10,100,110,100);
case 2:
g.drawLine(110,200,110,100);
case 1:
g.drawLine(10,200,10,100);
case 0:
g.drawLine(10,200,110,200);
}
}

public void run(){


while(true){
flag=(flag+1)%12;
repaint();
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}

/*
<applet code=TempleApplet width=400 height=400></applet>
*/
//Execution:- after compiling appletviewer TempleApplet.java
TYBCA Practical On Multithreading (File2)

Q4. Write a Multithreading program in Java for racing car. (Use AWT) slip7
Solution:-
import java.awt.*;
import java.awt.event.*;

class CarRace extends Frame{


private CarThread t1,t2;

public CarRace(){
setTitle("Car Racing");
setSize(500,300);
setLocation(100,100);
setVisible(true);

t1 = new CarThread();
t2 = new CarThread();

t1.start();
t2.start();

public void paint(Graphics g){


super.paint(g);

g.setColor(Color.RED);
g.fillRect(t1.getX(),70,75,45);

g.setColor(Color.GREEN);
g.fillRect(t2.getX(),150,75,45);
}

class CarThread extends Thread{


private int x;
public void run(){
while(true){
x++;
if(x>getWidth()) System.exit(0);

try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){}

repaint();
}
}

public int getX(){


return x;
}
}

public static void main(String args[]){


new CarRace();
}
}
TYBCA Practical On Multithreading (File2)

Q5.Write a multithreading program using Runnable interface to blink Text on the frame.
Solution:- Slip 8
import java.awt.*;
import java.awt.event.*;

class CarRace extends Frame{


private CarThread t1,t2;

public CarRace(){
setTitle("Car Racing");
setSize(500,300);
setLocation(100,100);
setVisible(true);

t1 = new CarThread();
t2 = new CarThread();

t1.start();
t2.start();

public void paint(Graphics g){


super.paint(g);

g.setColor(Color.RED);
g.fillRect(t1.getX(),70,75,45);

g.setColor(Color.GREEN);
g.fillRect(t2.getX(),150,75,45);
}

class CarThread extends Thread{


private int x;
public void run(){
while(true){
x++;
if(x>getWidth()) System.exit(0);

try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){}

repaint();
}
}

public int getX(){


return x;
}
}

public static void main(String args[]){


new CarRace();
}
}
TYBCA Practical On Multithreading (File2)

Q6. Write a Multithreading program in java using Runnable interface to move text on the
frame as follow: Starting Position of Text (See diagram in Practical slip)
Sol:- slip 9

import java.awt.*;
import java.awt.event.*;

class MovingText extends Frame implements Runnable{


private int x,y,w,h,f;

public MovingText(){
setTitle("Moving Text");
setSize(400,400);
setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

w = getWidth();
h = getHeight();

x = 0;
y = h/2;

Thread t = new Thread(this);


t.start();
}

public void run(){


while(true){
switch(f){
case 0:
x++;
y--;
if(x==w/2 && y==0) f=1;
break;
case 1:
x++;
y++;
if(x==w && y==h/2) f=2;
break;
case 2:
x--;
y++;
if(x==w/2 && y==h) f=3;
break;
case 3:
x--;
y--;
if(x==0 && y==h/2) f=0;
}
repaint();
try{
Thread.sleep(100);
}catch(Exception e){}
TYBCA Practical On Multithreading (File2)

}
}

public void paint(Graphics g){


super.paint(g);
g.drawString("Hello",x,y);
}

public static void main(String args[]){


new MovingText();
}
}

Q7. Write a Multithreading program in Java for bouncing ball. For each bounce, change the
color of ball randomly. Slip 10
Sol:-

import java.awt.*;
import java.awt.event.*;

class BouncingBall extends Frame implements Runnable{


private int x,y,w,h,f;
private Color c=Color.RED;

public BouncingBall(){
setTitle("Bouncing Balling");
setSize(400,400);
setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

w = getWidth();
h = getHeight();

x = (int)(Math.random()*w);
y = (int)(Math.random()*h);

Thread t = new Thread(this);


t.start();
}

public void run(){


while(true){
switch(f){
case 0:
y++;
if(y>h-50){
c = new Color((int)(Math.random()*256),
(int)(Math.random()*256),
TYBCA Practical On Multithreading (File2)

(int)(Math.random()*256));
f=1;
}
break;
case 1:
y--;
if(y<0){
c = new Color((int)(Math.random()*256),
(int)(Math.random()*256),
(int)(Math.random()*256));
f=0;
}
}
repaint();
try{
Thread.sleep(100);
}catch(Exception e){}
}
}

public void paint(Graphics g){


super.paint(g);
g.setColor(c);
g.fillOval(x,y,50,50);
}

public static void main(String args[]){


new BouncingBall();
}
}

Q8. Write a multithreading program in Java to display the numbers between 1 to 100
continuously in a TextField by clicking on button (Use Runnable interface) . Slip 12
Solution:-
import java.awt.*;
import java.awt.event.*;

class CounterThread extends Frame implements Runnable{


private TextField txtCount;
private Button btnStart;
private int count=1;
private Thread t;

public CounterThread(){
txtCount = new TextField(10);
btnStart = new Button("Start");

setTitle("Counter");
setSize(300,400);
setLayout(new FlowLayout());
add(txtCount);
add(btnStart);
setVisible(true);

t = new Thread(this);
TYBCA Practical On Multithreading (File2)

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

btnStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
t.start();
}
});
}

public void run(){


while(true){
txtCount.setText(Integer.toString(count));
count++;
if(count>100) count=1;

try{
Thread.sleep(1000);
}catch(Exception e){}
}
}

public static void main(String args[]){


new CounterThread();
}
}

Q9. Write a program in Java which will show lifecycle (creation, sleep, and dead) of a
thread. Program should print randomly the name of thread and value of sleep time. The
name of the thread should be hard coded through constructor. The sleep time of a thread
will be a random integer in the range 0 to 4999. Slip16
Sol:-

class MyThread extends Thread{

public MyThread(String s){


super(s);
}

public void run(){


System.out.println(getName()+" thread created.");
while(true){
System.out.println(this);
int s = (int)(Math.random()*5000);
System.out.println(getName()+" is sleeping for "+s+"msec");
try{
Thread.sleep(s);
}catch(Exception e){}
}
}
}
TYBCA Practical On Multithreading (File2)

class ThreadLifeCycle{
public static void main(String args[]){
MyThread t1 = new MyThread("Ram"),
t2 = new MyThread("Seeta");
t1.start();
t2.start();

try{
t1.join();
t2.join();
}catch(Exception e){}

System.out.println(t1.getName()+" thread dead.");


System.out.println(t2.getName()+" thread dead.");
}
}

Q10. Write a Java program using multithreading to execute the threads sequentially (Use
Synchronized Method) slip18 (also IMP for theory exam)
Sol:-

class Test{
public static synchronized void print(){
for(int i=1;i<=10;i++){
System.out.println(Thread.currentThread());
try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){}
}
}
}
class MyThread extends Thread{
public void run(){
Test.print();
}
}

class SynchronizedDemo{
public static void main(String args[]){
new MyThread().start();
new MyThread().start();
}
}

Q11. Write a Multithreading program in Java to convert smile face into the crying face
after 5 seconds and viceversa (Use Applet). Slip19
Sol:

import java.awt.*;
import java.applet.*;

public class FaceApplet extends Applet implements Runnable{


private Thread t;
TYBCA Practical On Multithreading (File2)

private boolean flag;

public void init(){


t = new Thread(this);
t.start();
}

public void run(){


while(true){
flag=!flag;
repaint();
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}

public void paint(Graphics g){


super.paint(g);

int w = getWidth();
int h = getHeight();

g.drawOval(20,20,w-40,h-40);
g.drawOval(w/2-75,h/2-75,30,30);
g.drawOval(w/2+75,h/2-75,30,30);

if(flag){
g.drawArc(w/2-75,h/2-30,150,60,180,180);
}
else{
g.drawArc(w/2-75,h/2-30,150,60,180,-180);
}
}
}

/*
<applet code=FaceApplet width=400 height=400></applet>
*/

//Execution:- after compiling appletviewer FaceApplet.java

Q12. Write a multithreading program in Java to create an applet that contains a TextField
to show time. The time should be displayed in the hh:mm:ss format. The thread should
start when the user clicks the Start button and stop when the user clicks the stop
button. Initialize the values to current time. [25]
Sol:-

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

public class StopWatchApplet extends JApplet{


TYBCA Practical On Multithreading (File2)

private JTextField txtTime;


private JButton btnStart,btnStop;

private MyThread t;

public void init(){


txtTime = new JTextField(10);
btnStart = new JButton("Start");
btnStop = new JButton("Stop");

btnStart.setMnemonic('S');
btnStop.setMnemonic('o');

btnStart.setToolTipText("Resume watch");
btnStop.setToolTipText("Suspend watch");

setLayout(new FlowLayout());
add(txtTime);
add(btnStart);
add(btnStop);

t = new MyThread();
t.start();

ButtonHandler bh = new ButtonHandler();


btnStart.addActionListener(bh);
btnStop.addActionListener(bh);
}

class ButtonHandler implements ActionListener{


public void actionPerformed(ActionEvent ae){
if(ae.getSource()==btnStart)
t.resume();
if(ae.getSource()==btnStop)
t.suspend();
}
}

class MyThread extends Thread{


public void run(){
while(true){
Date d = new Date();
txtTime.setText(
d.getHours()+":"+
d.getMinutes()+":"+
d.getSeconds());
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
}

/*<applet code=StopWatchApplet width=400 height=200></applet>*/

//Execution:- after compiling , appletviewer topWatchApplet.java

You might also like