A
Asit Dhal
Please check the following code...
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pc1;
/**
*
* @author asit
*/
import java.util.concurrent.Semaphore;
class Q {
int n;
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);
void get() {
try {
semCon.acquire();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got : " + n);
semProd.release();
}
void put(int n) {
try {
semProd.acquire();
}
catch(InterruptedException e) {
System.out.println("Caught InterrutedException ");
}
this.n = n;
System.out.println("Put : " + n);
semCon.release();
}
}
class Producer implements Runnable {
Q q;
Producer(Q p) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() { //line 58
for(int i=0; i<20; i++)
q.put(i);
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for(int i=0; i<20; i++)
q.get();
}
}
public class PC1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Q q = new Q();
new Consumer(q);
new Producer(q);
}
}
The above code gives me the following error.
run:
Exception in thread "Producer" java.lang.NullPointerException
at pc1.Producer.run(PC1.java:58)
at java.lang.Thread.run(Thread.java:619)
Please help me to find the error.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pc1;
/**
*
* @author asit
*/
import java.util.concurrent.Semaphore;
class Q {
int n;
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);
void get() {
try {
semCon.acquire();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got : " + n);
semProd.release();
}
void put(int n) {
try {
semProd.acquire();
}
catch(InterruptedException e) {
System.out.println("Caught InterrutedException ");
}
this.n = n;
System.out.println("Put : " + n);
semCon.release();
}
}
class Producer implements Runnable {
Q q;
Producer(Q p) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() { //line 58
for(int i=0; i<20; i++)
q.put(i);
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for(int i=0; i<20; i++)
q.get();
}
}
public class PC1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Q q = new Q();
new Consumer(q);
new Producer(q);
}
}
The above code gives me the following error.
run:
Exception in thread "Producer" java.lang.NullPointerException
at pc1.Producer.run(PC1.java:58)
at java.lang.Thread.run(Thread.java:619)
Please help me to find the error.