Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 78

EXPERIMENT 13

AIM: To Write a Program in java to check whether the given


string is palindrome or not.

PROGRAM:
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();

int length = str.length();


for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
EXPERIMENT-14

AIM: To sort a given list of names in ascending


order.
PROGRAM:
import java.util.*;
class Sorting
{
void sortStrings()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of n: ");
int n = s.nextInt();
String[] str = new String[n];
System.out.println("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String(s.next());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
System.out.println(str[i]);
}
}
}
class Sort
{
public static void main(String[] args)
{
Sorting obj = new Sorting();
obj.sortStrings();
}
}
EXPERIMENT 15
AIM: To write a java program that reads a line of integers and
then displays each integer and the sum of all integers.
PROGRAM:
import java.util.*;
class Sumtoken
{
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter sequence of integers with space b/w them and
press enter : ");
String digit=scr.nextLine();
StringTokenizer token=new StringTokenizer(digit);
int dig=0,sum=0;
System.out.println("\nEntered digits are : ");
while(token.hasMoreTokens())
{
String s=token.nextToken();
dig=Integer.parseInt(s);
System.out.print(dig+" ");
sum=sum+dig;
}
System.out.println();
System.out.println("Sum is : "+sum);
}}
EXPERIMENT:16
AIM: To create an abstract class named Shape,that contains an empty
method named numberOfSides().Provide three classes named
Trapezoid,Triangle,Rectangle and Hexagon such that each one of the
classes contains only the method numberOfSides(),that contains the
number of sides in the given geometrical figure.
PROGRAM:
abstract class Shape
{
abstract void numberofsides();
}
class Trapezoid extends Shape
{
void numberofsides()
{
System.out.println("Number of sides of Trapeziod is : 4");
}
}
class Triangle extends Shape
{
void numberofsides()
{
System.out.println("Number of sides of Triangle is : 3");
}
}
class Hexagon extends Shape
{
void numberofsides()
{
System.out.println("Number of sides of Hexagon is : 6");
}
}
class Sides
{
public static void main(String args[])
{
Shape s;
s=new Trapezoid();
s.numberofsides();
s=new Triangle();
s.numberofsides();
s=new Hexagon();
s.numberofsides();

}
}
EXPERIMENT:17
AIM: To write a java program to show dynamic polymorphism and
interfaces.
PROGRAM:
interface Bird
{
public abstract void eat(); // I
}
class Peacock implements Bird
{
public void eat() // II
{
System.out.println("Peacock eats grains");
}
}
class Vulture implements Bird
{
public void eat() // III
{
System.out.println("Vulture eats flesh");
}
}
class Crane implements Bird
{
public void eat() // IV
{
System.out.println("Crane eats fish");
}
}
public class DynamicPolyDemo
{
public static void main(String args[])
{
Bird b1; // reference variable of interface
Peacock p1 = new Peacock(); b1 = p1; b1.eat(); // calls II
Vulture v1 = new Vulture(); b1 = v1; b1.eat(); // calls III
Crane c1 = new Crane(); b1 = c1; b1.eat(); // calls IV
}
}
EXPERIMENT:18
AIM: To Create a Customized Exception and also make use of
all 5 exception keywords.
PROGRAM:
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
public class ExceptionKeywords {

// main() method - start of JVM execution


public static void main(String[] args) {

try {
// call division() method
String welcomeMessage = welcomeMessage("SJ");

// print to console
System.out.println("The returned welcome message : "
+ welcomeMessage);
}
catch (NullPointerException npex){
System.out.println("Exception handled : "
+ npex.toString());
}
finally {
System.out.println("Rest of the clean-up code here");
}
}

// division method returning quotient


public static String welcomeMessage(String name)
throws NullPointerException {

if(name == null) {

// explicitly throwing Null Pointer Error


// using throw keyword
throw new NullPointerException(
"Invoke method with VALID name");
}

// performing String concatenation


String welcomeMsg = "Welcome " + name;

/// return concatenated string value


return welcomeMsg;
}}
EXPERIMENT-19
AIM:To implement the use of super keyword.

PROGRAM:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class Super{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
EXPERIMENT-20
AIM: To implement the use of final keyword.

PROGRAM:
class FinalVariable

public static void main(String[] args)

final int hours=24;

System.out.println("Hours in 6 days = " + hours


* 6);

}
}
EXPERIMENT-21
AIM: To write an applet that computes the payment of a loan based
on the amount of the loan,the interest rate and the number of
months. It takes one parameter from the browser:Monthly
Rate,Interest Rate is per month,otherwise the interest rate is annual.

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Loan" width=300 height=300>
</applet>
*/
public class Loan extends Applet
implements ActionListener,ItemListener
{
double p,r,n,total,i;
String param1;
boolean month;
Label l1,l2,l3,l4;
TextField t1,t2,t3,t4;
Button b1,b2;
CheckboxGroup cbg;
Checkbox c1,c2;
String str;
public void init()
{
l1=new Label("Balance Amount",Label.LEFT);
l2=new Label("Number of Months",Label.LEFT);
l3=new Label("Interest Rate",Label.LEFT);
l4=new Label("Total Payment",Label.LEFT);
t1=new TextField(5);
t2=new TextField(5);
t3=new TextField(15);
t4=new TextField(20);
b1=new Button("OK");
b2=new Button("Delete");
cbg=new CheckboxGroup();
c1=new Checkbox("Month Rate",cbg,true);
c2=new Checkbox("Annual Rate",cbg,true);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(c1);
add(c2);
add(b1);
add(b2);
}
public void itemStateChanged(ItemEvent ie)
{
}
public void actionPerformed(ActionEvent ae)
{
str=ae.getActionCommand();
if(str.equals("OK"))
{
p=Double.parseDouble(t1.getText());
n=Double.parseDouble(t2.getText());
r=Double.parseDouble(t3.getText());
if(c2.getState())
{
n=n/12;
}
i=(p*n*r)/100;
total=p+i;
t4.setText(" "+total);
}
else if(str.equals("Delete"))
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
t4.setText(" ");
}
}
}
EXPERIMENT-22
AIM: To develop a program using the following AWT components in an applet-
TextField, TextArea, Button and Label

PROGRAM:
import java.awt.*;
import java.applet.*;
/* <applet code="AppletDemo.class" height=200 width=300>

</applet>*/

public class AppletDemo extends Applet


{
Button btn;
TextField txt;
Label lbl;
TextArea text;
public void init()
{
text = new TextArea("This is the text area");
btn=new Button("Button");
txt=new TextField("This is text field");
lbl=new Label("This is Label");
add(text);
add(btn);
add(txt);add(lbl);}}
EXPERIMENT-23
AIM:To make a simple Calculator.Use a grid layout to arrange buttons for the
digits and for the +,-,*,/,% operations.Add a text field to display the result.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Calculator" width=300 height=300></applet>*/
public class Calculator extends Applet implements ActionListener
{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{

String str=ae.getActionCommand();

if(str.equals("+")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("=")) { str1="";
if(oper.equals("+")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}

else if(oper.equals("-")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q))); }

else if(oper.equals("*")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q))); }

else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
}

else if(str.equals("C")){ p=0;q=0;


t.setText("");
str1="";
t.setText("0");
}

else{ t.setText(str1.concat(str));
str1=t.getText();
}

}
EXPERIMENT-24
AIM: Develop an analog clock using applet.
PROGRAM:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
/*<applet code="analogClock.class" width=300 height=300></applet>*/

public class analogClock extends Applet


{
public void init()
{
this.setSize(new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread()
{
public void run()
{

while (true)
{
repaint();
delayAnimation();
}
}
}.start();
}
private void delayAnimation()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void paint(Graphics g)
{
Calendar time = Calendar.getInstance();
int hour = time.get(Calendar.HOUR_OF_DAY);
int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
if (hour > 12) {
hour -= 12;
}

g.setColor(Color.white);
g.fillOval(300, 100, 200, 200);
g.setColor(Color.black);
g.drawString("12", 390, 120);
g.drawString("9", 310, 200);
g.drawString("6", 400, 290);
g.drawString("3", 480, 200);
double angle;
int x, y;
angle = Math.toRadians((15 - second) * 6);
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);
g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);
angle = Math.toRadians((15 - minute) * 6);
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);
g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);
angle = Math.toRadians((15 - (hour * 5)) * 6);

x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);

g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}
EXPERIMENT-25
AIM:To Develop a program demonstrating the use of Grid Layout in
an applet.Write the program which creates the frame and
implements Mouse Listener.
PROGRAM:
(1)Program for Grid Layout:
import java.awt.*;
import javax.swing.*;

public class GridDemo{


JFrame f;
GridDemo(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new GridDemo();
}
}
(2)Program for Mouse Listener:
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/*
* To create a stand alone window, class should be extended from
* Frame and not from Applet class.
*/

public class HandleMouseListenerInWindowExample extends Frame implements


MouseListener{
int x=0, y=0;
String strEvent = "";
HandleMouseListenerInWindowExample(String title){
super(title);
addWindowListener(new MyWindowAdapter(this));
addMouseListener(this);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
strEvent = "MouseClicked";
x = e.getX();
y = getY();
repaint();
}
public void mousePressed(MouseEvent e) {
strEvent = "MousePressed";
x = e.getX();
y = getY();
repaint();

}
public void mouseReleased(MouseEvent e) {
strEvent = "MouseReleased";
x = e.getX();
y = getY();
repaint();

}
public void mouseEntered(MouseEvent e) {
strEvent = "MouseEntered";
x = e.getX();
y = getY();
repaint();

}
public void mouseExited(MouseEvent e) {
strEvent = "MouseExited";
x = e.getX();
y = getY();
repaint();
}
public void paint(Graphics g){
g.drawString(strEvent + " at " + x + "," + y, 50,50);
}

public static void main(String[] args) {

HandleMouseListenerInWindowExample myWindow =
new HandleMouseListenerInWindowExample("Window With
Mouse Events Example");
}

class MyWindowAdapter extends WindowAdapter{

HandleMouseListenerInWindowExample myWindow = null;

MyWindowAdapter(HandleMouseListenerInWindowExample myWindow){
this.myWindow = myWindow;
}

public void windowClosing(WindowEvent we){


myWindow.setVisible(false);
}
}
EXPERIMENT-26
AIM: To write an application to simulate calculator using
GridBagLayout.
PROGRAM:
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;

public class Calculator1 extends JFrame


{JButton but1, but2, but3, but4, but5, but6,
but7, but8, but9, but0, butPlus, butMinus,
clearAll;
JTextField textResult;

int num1, num2;


public static void main(String[] args)
{
new Calculator1();
}
public Calculator1()
{
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Calculator");
JPanel thePanel = new JPanel();
thePanel.setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.gridwidth = 1;
gridConstraints.gridheight = 1;
gridConstraints.weightx = 50;
gridConstraints.weighty = 100;
gridConstraints.insets = new Insets(5,5,5,5);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.fill = GridBagConstraints.BOTH;
textResult = new JTextField("0",20);
Font font = new Font("Helvetica", Font.PLAIN, 18);
textResult.setFont(font);

but1 = new JButton("1");


but2 = new JButton("2");
but3 = new JButton("3");
but4 = new JButton("4");
but5 = new JButton("5");
but6 = new JButton("6");
but7 = new JButton("7");
but8 = new JButton("8");
but9 = new JButton("9");
butPlus = new JButton("+");
but0 = new JButton("0");
butMinus = new JButton("-");
clearAll = new JButton("C");
thePanel.add(clearAll,gridConstraints);
gridConstraints.gridwidth = 20;
gridConstraints.gridx = 5;
thePanel.add(textResult,gridConstraints);
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
thePanel.add(but1,gridConstraints);
gridConstraints.gridx = 5;
thePanel.add(but2,gridConstraints);
gridConstraints.gridx = 9;
thePanel.add(but3,gridConstraints);
gridConstraints.gridx = 1;
gridConstraints.gridy = 3;
thePanel.add(but4,gridConstraints);
gridConstraints.gridx = 5;
thePanel.add(but5,gridConstraints);
gridConstraints.gridx = 9;
thePanel.add(but6,gridConstraints);
gridConstraints.gridx = 1;
gridConstraints.gridy = 4;
thePanel.add(but7,gridConstraints);
gridConstraints.gridx = 5;
thePanel.add(but8,gridConstraints);
gridConstraints.gridx = 9;
thePanel.add(but9,gridConstraints);
gridConstraints.gridx = 1;
gridConstraints.gridy = 5;
thePanel.add(butPlus,gridConstraints);
gridConstraints.gridx = 5;
thePanel.add(but0,gridConstraints);
gridConstraints.gridx = 9;
thePanel.add(butMinus,gridConstraints);
this.add(thePanel);
this.setVisible(true);

}
EXPERIMENT-27
AIM:To develop a program to set a given string in desired font and
color.
PROGRAM:
import java.awt.event.*;
import javax.swing.*;

public class Main extends JPanel {


String[] type = { "Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
String[] stylenames = { "Arial", "Italic", "Bold", "Bold & Italic" };

public void paint(Graphics g) {


for (int f = 0; f < type.length; f++) {
for (int s = 0; s < styles.length; s++) {
Font font = new Font(type[f], styles[s], 18);
g.setFont(font);
String name = type[f] + " " + stylenames[s];
g.drawString(name, 20, (f * 4 + s + 1) * 20);
}
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}
EXPERIMENT-28
AIM:To develop a program to create member with various menu
items and submenu items.
PROGRAM:
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
EXPERIMENT-29
AIM:To develop a program to handle Keyboard Events.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key.class" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{g.drawString(msg,X,Y);
}}
EXPERIMENT-30
AIM:To display the number of characters,lines and words in a text.
PROGRAM:
import java.io.*;

public class Test


{
public static void main(String[] args) throws IOException
{
File file = new File("Test.txt");
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);

String line;

// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;

// Reading line by line from the


// file until a null is returned
while((line = reader.readLine()) != null)
{
if(line.equals(""))
{
paragraphCount++;
}
if(!(line.equals("")))
{

characterCount += line.length();

// \\s+ is the space delimiter in java


String[] wordList = line.split("\\s+");

countWord += wordList.length;
whitespaceCount += countWord -1;

// [!?.:]+ is the sentence delimiter in java


String[] sentenceList = line.split("[!?.:]+");

sentenceCount += sentenceList.length;
}
}

System.out.println("Total word count = " + countWord);


System.out.println("Total number of sentences = " + sentenceCount);
System.out.println("Total number of characters = " + characterCount);
System.out.println("Number of paragraphs = " + paragraphCount);
System.out.println("Total number of whitespaces = " + whitespaceCount);
}}
EXPERIMENT-31
AIM:To develop a program demonstrate the use of URL Connection.
PROGRAM:
import java.net.*;
import java.io.*;

public class URLDemo {

public static void main(String [] args) {


try {
URL url = new URL("https://www.amrood.com/index.htm?language=en#j2se");

System.out.println("URL is " + url.toString());


System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
} catch (IOException e) {
e.printStackTrace();
}
}
}
EXPERIMENT-33
AIM:To create two threads one for even and other for odd.
PROGRAM:
public class Mythread {
public static void main(String[] args) {
Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}

class Runnable2 implements Runnable{


public void run(){
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 0)
System.out.println(i); }}}
EXPERIMENT-34
AIM:To implement the producer consumer problem using the
concept of inter thread communication.
PROGRAM:
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
t1.start();
t2.start();

t1.join();
t2.join();
}
public static class PC
{

LinkedList<Integer> list = new LinkedList<>();


int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{

while (list.size()==capacity)
wait();

System.out.println("Producer produced-"
+ value);

list.add(value++);

notify();

Thread.sleep(1000);
}
}
}

public void consume() throws InterruptedException


{
while (true)
{
synchronized (this)
{

while (list.size()==0)
wait();

int val = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);

notify();
Thread.sleep(1000);
}
}
}
}
}
EXPERIMENT-35
AIM: To create three threads by extending Thread class.First thread
displays “Good Morning” every 1 sec,the second thread displays
“Hello” every 2 seconds and the third thread displays “Welcome”
every 3 seconds.

PROGRAM:
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{}
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{}
}
}
class ThreeThreads
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}

You might also like