java thread nullPointerException

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top