Trying to solve consumer-producer in java with multithreading -
i'm trying solve producer consumer problem threads in java, code won't run in parallell/concurrently. producer fills buffer before consumer starts consume, , don't why. point trying using synchronized blocks, wait() , notify().
main :
string [] data = {"fisk", "katt", "hund", "sau", "fugl", "elg", "tiger", "kameleon", "isbjørn", "puma"}; producerconsumer pc = new producerconsumer(5); thread[] thrds = new thread[2]; thrds[0] = new thread(new mythread1(pc, data)); // producer thrds[1] = new thread(new mythread2(pc)); // consumer thrds[0].start(); thrds[1].start(); for(int = 0; < 2; i++) { // wait threads die try { thrds[i].join(); } catch (interruptedexception ie) {} } system.exit(0);
producerconsumer.java:
import java.util.linkedlist; import java.util.queue; public class producerconsumer implements runnable { private int buffersize; private queue<string> buffer; public producerconsumer(int size) { buffersize = size; buffer = new linkedlist<string>(); } public void produce(string item) throws interruptedexception { synchronized(buffer) { while (buffer.size() >= buffersize) { try { system.out.println("full buffer. waiting consumer..."); buffer.wait(); }catch (exception e) {} } buffer.add(item); system.out.println("producer putting " + item + " in buffer"); buffer.notify(); } } public void consume() throws interruptedexception { synchronized (buffer) { while (buffer.size() == 0) { try { system.out.println("empty buffer. waiting production..."); buffer.wait(); }catch (exception e) {} } system.out.println("consumer consuming " + buffer.remove() + "."); buffer.notify(); } } @override public void run() { }
}
mythread1 :
/* * producer - thread */ public class mythread1 implements runnable { private string [] data; private producerconsumer pc; public mythread1(producerconsumer pc, string [] data) { this.pc = pc; this.data = data; } @override public void run() { (int = 0; < data.length; i++) { try { pc.produce(data[i]); } catch (interruptedexception ex) {} } } }
mythread2:
//the consumer - thread
public class mythread2 implements runnable{ private producerconsumer pc; public mythread2(producerconsumer pc) { this.pc = pc; } //run consume @override public void run() { while (true) { try { pc.consume(); thread.sleep(2); } catch(interruptedexception e) {} } } }
on recent machines, short queues this, never see actual multithreading effects like, in case, producer , consumer taking turns unless slow both of them down bit. slowed down consumer. instead of using short array, put million integers in queue , see happens.
Comments
Post a Comment