简体   繁体   中英

Wait notify multithreading producer consumer issue

I was working on a basic thread-producer consumer problem.

now in my this code what i am assuming is 1) The threads will go to wait state initially and the moment any task comes one of the tasks will be notified and it will process that task and then again wait but my threads are going to runnable states abruptly. Is my understanding correct?

public static void main(String[] args) {
    AsyncTaskExecutorImpl executorImpl = new AsyncTaskExecutorImpl(10, 5);

    for (int i = 0; i < 200; i++) {

        Runnable task = new createTask();
        System.out.println("Added task no" + i);
        executorImpl.execute(task, 10);
    }
}



import java.util.concurrent.ArrayBlockingQueue;

public class MyArrayBlockingQueue<T> {
private volatile ArrayBlockingQueue<Runnable> internalTaskQueue = new ArrayBlockingQueue<Runnable>(
        10);


public boolean isEmpty() {
    synchronized (this) {
        return internalTaskQueue.isEmpty();
    }
}

public void add(Runnable paramRunnable) throws InterruptedException {
    synchronized (this.internalTaskQueue) {
        this.internalTaskQueue.put(paramRunnable);
        this.internalTaskQueue.notifyAll();

    }

    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getName().startsWith("T") || t.getName().startsWith("M")) {
            System.out.println(t.getName() + "----" + t.getState());
        }
    }

}

public Runnable poll() {

    Runnable task = null;
    try {
        synchronized (this.internalTaskQueue) {
            while (this.internalTaskQueue.isEmpty()) {

                this.internalTaskQueue.wait();

            }
            task = this.internalTaskQueue.poll();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return task;
}
}`
 import java.util.concurrent.Callable;
 import java.util.concurrent.Future;

 import org.springframework.core.task.AsyncTaskExecutor;

 public class AsyncTaskExecutorImpl implements AsyncTaskExecutor {

private  MyArrayBlockingQueue<Runnable> taskQueue= new MyArrayBlockingQueue<Runnable>();

// Here we are creating a Thread pool of number of threads required
public AsyncTaskExecutorImpl(int no_of_threads, int taskQueueSize) {

    for (int i = 0; i < no_of_threads; i++) {
        IndividualThread thread = new IndividualThread(this.taskQueue);
        thread.start();
    }

    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getName().startsWith("T") || t.getName().startsWith("M")) {
            System.out.println(t.getName() + "----" + t.getState());
        }
    }
}

@Override
public void execute(Runnable paramRunnable, long paramLong) {
    if (paramRunnable instanceof Runnable) {

        // pick any thread from the threadpool and then execute that
        try {
            this.taskQueue.add(paramRunnable);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}`
class CreateTask implements Runnable {
@Override
public void run() {

    System.out.println(Thread.currentThread().getName() + "got the task");

}

NotifyAll would "wake up" all waiting threads. But it should be logically ok because they would then compete to get into 'sychronized' block , the 1st thread that gets access will find 'not empty', pull the data, exit the 'synchornized' block.
Then some other thread would get into the synchronized block, but by then it would see 'empty' & immediately get back to waiting (unless there were several 'add' actions, of course, in which case several threads would see 'not empty'). In other words, if your spin lock is correctly designed, threads would become Runnable for a brief fraction of a second.

There's also 'Object.notify' that would wake up only one thread, but AFAIK it's considered unsafe for spin-locks such as yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM