Java Notes
Java Notes
) catch (InterruptedException e) {
System. out.println (name + "Interrupted") ;
class Multi {
public static void main(String args[]) {
new NewThread("One"); / start threads
new NewThread ("Two") ;
new NewThread ("Three");
try {
Thread.sleep (10000);
) catch (InterruptedException e) {
System. out.println ( "Main thread Interrupted") :
System., out.println("Main thread exiting. ")
)
Producer Consumer Problem:
Let's now work through an example that uses wait( ) and notify( ). To begin, consider the following sample
program that incorrectly implements a simple form of the producer/ consumer problem. It consists of four
classes: Q, the queue that you're trying to synchronize; Producer, the threaded object that is producing
queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the tiny class that
creates the single Q, Producer, and Consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get() (
while(!valueSet)
try (
wait():
}catch(InterruptedException e) {
System.out.printin("InterruptedException caught"):
valueSet= false;
notify():
return n;
Ontout:
Put: 0
Press Control-c to stop.
Got: 0
Put: 1
Got: 1
Put :
Got: 2
Put:3
Got:3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
Put: 7
Got: 7
Put: 8
Got: 8
Put: 9
Got: 9
public MyThread (String name) {
super(nane);
eOverride
public void run()
1| Set priorities
thread1. setPriority(Thread. MTN_ PRIORITY); I/ 1
thread2.setPriority(Thread, MAX_PRIORIT); / 10
1| Start the threads
thread1.start();
thread2,start ();
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
class Oemo enteds Exapton
f
Divi~im nt fotlibla
Finally block exeuted
chained Excphimns
amothes encafion itd an eruftion: the deiand exafhon
Aithkebaftm al=he
S.o.Pals):