Я работал над основной проблемой потребителей нитей.Ждите уведомления о проблеме многопоточности производителя.
сейчас в моем этом коде, что я предполагаю, является 1) Потоки будут идти, чтобы ждать состояния изначально, и в тот момент, когда какая-либо задача придет, одна из задач будет извещена и будет обрабатывать эту задачу, а затем снова ждать, но мой потоки внезапно перейдут в управляемые состояния. Правильно ли я понимаю?
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");
}
Что это за строка 'new createTask();'? Можно ли начинать имена классов с нижнего регистра? – selalerer
@selalerer да его класс любезно игнорирует эту ошибку опечатки. Я добавил класс CreateTask. –
@AnilSharma в чем ваш вопрос? Есть ли ошибка в коде или вы хотите понять, как это работает? – Dien