class CI(b) Explain utility class Hashtable and instanceof operator by giving examples.
{
int n;
boolean valueSet = false;
synchronized int recieve()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Recieve : " + n);
valueSet = false;
notify();
return n;
}
synchronized void send(int n)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Send : "+n);
notify();
}
}
class Producer implements Runnable
{
CI ci;
Producer(CI ci)
{
this.ci = ci;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
ci.send(i++);
}
}
}
class Consumer implements Runnable
{
CI ci;
Consumer(CI ci)
{
this.ci = ci;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
ci.recieve();
}
}
}
class multithreadedProgramProducerConsumerExampleH2E
{
public static void main(String args[])
{
CI ci = new CI();
new Producer(ci);
new Consumer(ci);
System.out.println("Press Control-C to Stop.");
}
}
// utility class Hashtable Example import java.io.*;
import java.util.*;
class utilityClassHashtableExampleH2E
{
public static void main(String args[]) throws IOException
{
Hashtable<String,Integer> ht = new Hashtable<String,Integer>();
ht.put("Jaydip",88);
ht.put("Arpan",89);
ht.put("Praik",90);
System.out.println("The Students names : ");
Enumeration e = ht.keys();
while(e.hasMoreElements())
System.out.println(e.nextElement());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Student Name : ");
String name = br.readLine();
name = name.trim();
Integer mark = ht.get(name);
if(mark != null)
{
int mv = mark.intValue();
System.out.println(name + " mark : "+mv);
}
else
System.out.println("Student Not Found");
}
}
// Instanceof Operator Example class A
{
int i,j;
}
class B
{
int i,j;
}
class C extends A
{
int k;
}
class D extends A
{
int k;
}
class instanceofOperatorExampleH2E
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(d instanceof D)
System.out.println("d is instance of D");
System.out.println();
A ob;
ob = d;
System.out.println("ob is now refers to d");
System.out.println();
if(ob instanceof D)
System.out.println("ob is instance of D");
ob = c;
System.out.println();
System.out.println("ob is now refers to C");
System.out.println();
if(ob instanceof D)
System.out.println("ob can cast to D");
else
System.out.println("ob can not cast to D");
}
}