Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #7272

java thread nullPointerException

From Asit Dhal <lipun4u@gmail.com>
Newsgroups comp.lang.java.programmer
Subject java thread nullPointerException
Date 2011-08-21 02:50 -0700
Organization http://groups.google.com
Message-ID <ea0601c8-ebe5-48aa-9dc0-ebd2d88d19b9@glegroupsg2000goo.googlegroups.com> (permalink)

Show all headers | View raw


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.

Back to comp.lang.java.programmer | Previous | NextNext in thread | Find similar


Thread

java thread nullPointerException Asit Dhal <lipun4u@gmail.com> - 2011-08-21 02:50 -0700
  Re: java thread nullPointerException Jeff Higgins <jeff@invalid.invalid> - 2011-08-21 06:49 -0400
    Re: java thread nullPointerException Asit Dhal <lipun4u@gmail.com> - 2011-08-21 10:21 -0700
  Re: java thread nullPointerException Roedy Green <see_website@mindprod.com.invalid> - 2011-08-22 07:56 -0700

csiph-web