I have two threads, A and B. A has to create messages and store them in a list in memory and B has to read the first message from the same list in memory, remove it from the list and do something with it.
A and B start with a main thread.
My question is how can I make a list that is shared by two different threads?
You should read this: https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/
And the Java sample they have there should help with some modifications for your scenario.
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();
//to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
As others have advised, I think you should spend some time understanding threading and producer consumer pattern.
First create an instance of the list.
Second pass the list as argument to the constructor of both runnables.
public static void main(String args[]){
List<MyType> myList = new ArrayList<>();
Runnable r1 = new MyRunnable(myList);
Runnable r2 = new MyRunnable(myList);
new Thread(r1).start();
new Thread(r2).start();
}
public class MyRunnable implements Runnable {
List list;
public MyRunnable(List list) {
this.list = list;
}
#Override
public void run() {}
}
Related
I use semaphore and I want when list size is zero thread waiting for other thread But Why doesn't the semaphore stop thrading? Doesn't the semaphore work like notify and wait?
result:
add
remove
add
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
ArrayList<String> list = new ArrayList<>();
Semaphore semaphore = new Semaphore(0);
new Producer(list, semaphore).start();
new Producer(list, semaphore).start();
new Customeer(list, semaphore).start();
new Customeer(list, semaphore).start();
//////////
static class Customeer extends Thread {
private List<String> list;
private Semaphore semaphore;
public Customeer(List<String> list, Semaphore semaphore) {
this.list = list;
this.semaphore = semaphore;
}
#Override
public void run() {
synchronized (list) {
if (list.size() == 0) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove(0);
System.out.println("remove");
}
}
}
static class Producer extends Thread {
private Semaphore semaphore;
private List<String> list;
public Producer(List<String> list, Semaphore semaphore) {
this.list = list;
this.semaphore = semaphore;
}
#Override
public void run() {
synchronized (list) {
list.add("hello");
semaphore.release();
System.out.println("add");
}
}
}
}
you seem to be confused with semaphores and synchronization. semaphores is used when you want to allow n threads to access the same resource at a time. [n can be 1] while synchronization is used if you want to allow only 1 thread to access the resource.
solution using semaphores
// Java implementation of a producer and consumer
// that use semaphores to control synchronization.
import java.util.concurrent.Semaphore;
class Q {
// an item
int item;
// semCon initialized with 0 permits
// to ensure put() executes first
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);
// to get an item from buffer
void get()
{
try {
// Before consumer can consume an item,
// it must acquire a permit from semCon
semCon.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
// consumer consuming an item
System.out.println("Consumer consumed item : " + item);
// After consumer consumes the item,
// it releases semProd to notify producer
semProd.release();
}
// to put an item in buffer
void put(int item)
{
try {
// Before producer can produce an item,
// it must acquire a permit from semProd
semProd.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
// producer producing an item
this.item = item;
System.out.println("Producer produced item : " + item);
// After producer produces the item,
// it releases semCon to notify consumer
semCon.release();
}
}
// Producer class
class Producer implements Runnable {
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
for (int i = 0; i < 5; i++)
// producer put items
q.put(i);
}
}
// Consumer class
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 < 5; i++)
// consumer get items
q.get();
}
}
// Driver class
class PC {
public static void main(String args[])
{
// creating buffer queue
Q q = new Q();
// starting consumer thread
new Consumer(q);
// starting producer thread
new Producer(q);
}
}
solution using synchronized
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable() {
#Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
#Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC {
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();
// to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
read the resources for more clarity
semaphore: https://www.geeksforgeeks.org/producer-consumer-solution-using-semaphores-java/
synchronized: https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/
I have a thread that adds connections to a list. My application needs to do pick 2 random elements when the list gets bigger then two elements.
After that the program does some actions on the connections and then removes the two connections out of the list.
I already tried to make a separate thread run and check if the list is bigger then 2 elements.
When its bigger it picks 2 random elements out of the list and does the action with them, and then removes them from the list.
Is there a better way to do this in a design pattern way? I don't think that running another thread that keeps checking if list is bigger then 2 is a good solution.
You can achieve your solution with producer consumer problem where one thread is checking the size of List and when the size reaches 2 then other threads starts consuming(removing) from the list. Both addition and removal to the thread should be performed through the synchronized blocks so that no discrepancy happens.
You can try below approach for your problem.
`
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args) throws InterruptedException {
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumer (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();
//to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
`
have a look here
https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/
public class SemaphoreWithQueues implements Semaphore {
private List<Object> queue;
private AtomicInteger current = new AtomicInteger(0);
private int permits;
public SemaphoreWithQueues(int permits) {
this.permits = permits;
this.queue = Collections.synchronizedList(new LinkedList<>());
}
#Override
public void enter() throws InterruptedException {
if (current.get() < permits) {
current.incrementAndGet();
} else {
Object block = new Object();
synchronized (block) {
queue.add(block);
block.wait();
current.incrementAndGet();
}
}
}
#Override
public void leave() {
if(queue.size() != 0) {
Object block = queue.get(0);
queue.remove(0);
synchronized (block) {
block.notify(); //Unblock quenue
}
}
current.decrementAndGet();
//current lessen and current thread have time come in block if(...)
// in enter() faster then another thread increased current
}
}
> The program usually output:
>
> 1 1 2 2 1 1 2 2 1 2
**Where run() of both threads is almost the same, such as:**
public void run(){
for (int i = 0; i <5; i++) {
try {
semaphore.enter();
} catch (InterruptedException e) {
System.err.println(e);
}
System.out.println(2);
semaphore.leave();
}
}
There are 2 threads using this semaphore. When 1 thread increases the queue, the second is waiting, the problem is that if we extracted the object from quene and unblocked it, then the thread that finished leave() start enter() faster and again increments the counter, while the awaked thread also increments the counter, current = 2, and the list is empty.
SORRY FOR BAD ENGLISH
There are many problems in the code.
Synchronization: Synchronization should be done for a shareable
resource. Why it is done for a local object which has scope only for
that method.
Object block = new Object();
synchronized (block) {
Both current and queue are independent properties, they should be
synchronized together.
Now let's come to point If you really want to create a semaphore using Queue. You do not need all this logic. You can use existing Java class e.g. BlockingQueue. Here is the implementation
class SemaphoreWithQueues implements Semaphore{
private BlockingQueue<Integer> queue;
public SemaphoreWithQueues(int permits) {
if(queue == null){
queue = new ArrayBlockingQueue<>(permits);
}
}
public void enter() {
queue.offer(1);
System.out.println(Thread.currentThread().getName() + " got a permit.");
}
public void leave() throws InterruptedException {
queue.take();
System.out.println(Thread.currentThread().getName() + " left the permit.");
}
}
And Task to use the semaphore
class Task implements Runnable {
private SemaphoreWithQueues semaphore;
public Task(SemaphoreWithQueues semaphore){
this.semaphore = semaphore;
}
public void run(){
for (int i = 0; i <5; i++) {
semaphore.enter();
try {
semaphore.leave();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
SemaphoreWithQueues semaphoreWithQueues = new SemaphoreWithQueues(5);
Thread th1 = new Thread(new Task(semaphoreWithQueues));
Thread th2 = new Thread(new Task(semaphoreWithQueues));
Thread th3 = new Thread(new Task(semaphoreWithQueues));
th1.start();
th2.start();
th3.start();
}
}
But personally I do not like using Queue to create Semaphores, as it wastes memory unnecessary by creating elements in queue. Despite of this you can create a semaphore using single shareable object with permits using wait and notify mechanism. You can try with this approach. If you would like.
The code in this question was clearly too long so I've written an example you can just copy and paste that I think encompasses the conceptual problem I'm having.
Thanks to those who read all the way through the previous version!
Two files
One calls the other and passes an ArrayList.
The 2nd file alters the ArrayList and provides a getter for the first file to access the altered file.
How can I make the first file wait for the processing in the second file, before calling the getter. At the moment this code gives you a NullPointerException because the first file isn't waiting.
join() on the thread of execution doesn't seem to work, and if I use wait(), how do I notify() to the first file from the second file?
Here's the code:
public class Launcher implements Runnable {
private ArrayList al = new ArrayList();
private ArrayProcessor ap;
public Launcher(ArrayList al){
this.al = al;
ArrayProcessor ap = new ArrayProcessor(al);
}
public static void main(String[] args){
ArrayList anArray = new ArrayList();
anArray.add(new Integer(1));
anArray.add(new Integer(13));
anArray.add(new Integer(19));
Launcher l = new Launcher(anArray);
l.liftOff();
}
public void liftOff(){
Thread t = new Thread(new Launcher(al));
synchronized(t){
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.ap = new ArrayProcessor(al);
System.out.println("the array: " + ap.getArray());
}
public void run() {
ap.doProcess(al);
}
}
and the called file:
public class ArrayProcessor extends Thread{
private ArrayList al;
public ArrayProcessor(ArrayList al){
this.al = al;
}
public void doProcess(ArrayList myAL){
this.start();
}
public void run() {
// this should increment the ArrayList elements by one
for (int i=0; i<al.size(); i++){
int num = ((Integer)al.get(i)).intValue();
al.set(i, new Integer(++num));
}
}
public ArrayList getArray(){
return al;
}
}
If you want one thread wait for another to finish you could use a CountDownLatch. Since there is a lot of code in your samples, here is a small POC:
public static void main(String[] args) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
#Override
public void run() {
try {
System.out.println("Thread doing some work...");
Thread.sleep(10 * 1000);
System.out.println("Thread done!");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
System.out.println("Main Thread waiting...");
latch.await();
System.out.println("Main Thread can continue");
}
How to pass parameter to an already running thread in java -- not in the constructor, & probably without using wait() (possible ??)
Something similar to a comment in How can I pass a parameter to a Java Thread?
Do you mean passing a parameter to an already running thread ? Because all the current answers are about passing parameters to new threads... – Valentin Rocher May 18 '09 at 10:43
[edited]
yes, I was looking for something like the producer/consumer pattern.
I wanted something like a thread in which has the processing & is ready
for keyboard input. The other thread is just to monitor network and pass
on the received text to the processing thread.
Maybe what you really need is blocking queue.When you create the thread, you pass the blocking queue in and the thread should keep checking if there is any element in the queue. Outside the thread, you can put elements to the queue while the thread is "running". Blocking queue can prevent the thread from quit if their is nothing to do.
public class Test {
public static void main(String... args) {
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
Thread running = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
String data = queue.take();
//handle the data
} catch (InterruptedException e) {
System.err.println("Error occurred:" + e);
}
}
}
});
running.start();
// Send data to the running thread
for (int i = 0; i < 10; i++) {
queue.offer("data " + i);
}
}
}
The "other thread" will have its own life, so you can't really communicate with it / pass parameters to it, unless it actively reads what you gives to it.
A thread which you allows you to communicate with it typically reads data from some buffered queue.
Have a look at ArrayBlockingQueue for instance, and read up on the Consumer-Producer pattern.
public class T1 implements Runnable {
//parameter of thread T1
public static AtomicBoolean flag = new AtomicBoolean();
#Override
public void run() {
}
}
public class T2 implements Runnable {
#Override
public void run() {
//parameter to an already running thread
T1.flag.set(true);
}
}
What about such way:
class TestRun implements Runnable
{
private int testInt = -1;
public void setInt(int i)
{
this.testInt = i;
}
#Override
public void run()
{
while (!isFinishing())
{
System.out.println("Working thread, int : " + testInt);
try
{
Thread.sleep(2500);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
.....
TestRun first = new TestRun();
TestRun second = new TestRun();
(new Thread(first)).start();
(new Thread(second)).start();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
first.setInt(101);
second.setInt(102);