Skip to content

Add files via upload #6227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions src/BlockQueue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.thealgorithms.datastructures.threadPool;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BlockQueue<T> {

private final Deque<T> deque = new ArrayDeque<>();
private final int capacity;
private final ReentrantLock lock = new ReentrantLock();
//This condition object is used to manage thread waiting when the queue is full
private final Condition full = lock.newCondition();
//This condition object is used to manage thread waiting when the queue is empty
private final Condition empty = lock.newCondition();

public BlockQueue(int capacity) {
this.capacity = capacity;
}


// add task
public void put(T task) {
lock.lock();
lock.lock();
try {
while (deque.size() == capacity) {
//If the queue is full, the thread that calls this method will be blocked until space becomes available in the queue.
full.await();
}
deque.addLast(task);
//Wake up threads that might be waiting due to the queue being empty.
empty.signal();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for space in the queue", e);
} finally {
lock.unlock();
}

}

// Block and add with a timeout
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (deque.size() == capacity) {
if (nanos <= 0) {
return false;
}
nanos = full.awaitNanos(nanos);
}
deque.addLast(task);
empty.signal();
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
lock.unlock();
}
}


public T take() {
lock.lock();
try {
while (deque.isEmpty()) {
empty.await();
}
T task = deque.removeFirst();
full.signal();
return task;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for elements in the queue", e);
} finally {
lock.unlock();
}
}


public T poll(long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (deque.isEmpty()) {
if (nanos <= 0) {
return null;
}
nanos = empty.awaitNanos(nanos);
}
T task = deque.removeFirst();
full.signal();
return task;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} finally {
lock.unlock();
}


}


public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
if (deque.size() == capacity) {
rejectPolicy.reject(this, task);
} else {
deque.addLast(task);
empty.signal();
}
} finally {
lock.unlock();
}

}
}
8 changes: 8 additions & 0 deletions src/RejectPolicy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.thealgorithms.datastructures.threadPool;


public interface RejectPolicy<T> {

void reject(BlockQueue<T> blockQueue, T e);

}
127 changes: 127 additions & 0 deletions src/ThreadPool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package com.thealgorithms.datastructures.threadPool;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* A simple thread pool implementation.
*/
public class ThreadPool {

private final BlockQueue<Runnable> blockQueue;
private final Set<Worker> workers = new HashSet<>();
private final int corePoolSize;
private final long keepAliveTime;
private final TimeUnit timeUnit;
private final RejectPolicy<Runnable> rejectPolicy;

/**
* Constructs a new ThreadPool with the given parameters.
*
* @param blockQueue the blocking queue to hold tasks
* @param corePoolSize the number of core threads
* @param keepAliveTime the time to keep extra threads alive
* @param timeUnit the time unit for keepAliveTime
* @param rejectPolicy the policy to handle rejected tasks
*/
public ThreadPool(BlockQueue<Runnable> blockQueue, int corePoolSize, long keepAliveTime, TimeUnit timeUnit, RejectPolicy<Runnable> rejectPolicy) {
this.blockQueue = blockQueue;
this.corePoolSize = corePoolSize;
this.keepAliveTime = keepAliveTime;
this.timeUnit = timeUnit;
this.rejectPolicy = rejectPolicy;
}

public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(new BlockQueue<>(5), 2, 5, TimeUnit.SECONDS,
(queue, task) -> {
// Discard the task
System.out.println("Task " + task + " rejected.");
});


for (int i = 0; i < 10; i++) {
final int taskId = i;
threadPool.execute(() -> {
System.out.println("Task " + taskId + " is running on thread: " + Thread.currentThread().getName());
try {
// Simulate some work
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Task " + taskId + " completed.");
});
}

// Wait for a while to let all tasks complete
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}



}

/**
* Executes a task using the thread pool.
*
* @param task the task to execute
*/
public void execute(Runnable task) {
synchronized (workers) {
if (workers.size() < corePoolSize) {
// Create a new worker thread
Worker worker = new Worker();
workers.add(worker);
worker.start();
} else {
/*
* Try to put the task into the block queue
* */
blockQueue.tryPut(rejectPolicy, task);
}
}
}

/**
* Worker thread class.
*/
class Worker extends Thread {

private volatile boolean running = true;

public Worker() {
super("Worker-" + workers.size());
}

@Override
public void run() {
while (running) {
Runnable task = null;
try {
// Get a task from the block queue
task = blockQueue.poll(keepAliveTime, timeUnit);
if (task != null) {
task.run();
}
} catch (Exception e) {
throw new RuntimeException("Error executing task", e);
} finally {
if (task == null || !running) {
synchronized (workers) {
workers.remove(this);
}
}
}
}
}

public void shutdown() {
running = false;
}
}
}
83 changes: 83 additions & 0 deletions src/main/java/com/thealgorithms/matrix/MatrixEigenvalues.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.thealgorithms.matrix;

import java.util.ArrayList;

//This is a method for solving for the matrix eigenvalue with the largest absolute value
public final class MatrixEigenvalues {

private MatrixEigenvalues(){

}

public static void main(String[] args) {
ArrayList<ArrayList<Double>> matrix = new ArrayList<>();
matrix.add(new ArrayList<Double>() {{ add(-3.0); add(1.0); add(-1.0);}});
matrix.add(new ArrayList<Double>() {{ add(-7.0); add(5.0);add(-1.0); }});
matrix.add(new ArrayList<Double>() {{ add(-6.0); add(6.0);add(-2.0); }});
// Calculate the largest eigenvalue
Double eigenvalues = powerIteration(matrix, 1000, 1e-10);


System.out.println("largest eigenvalue:"+eigenvalues);

}
// Power iteration method for computing the largest eigenvalue and eigenvecto
public static Double powerIteration(ArrayList<ArrayList<Double>> matrix, int maxIterations, double tolerance) {
int n = matrix.size();
ArrayList<Double> vector = new ArrayList<>();
for (int i = 0; i < n; i++) {
vector.add(i == 0 ? 1.0 : 0.0); // 初始化向量
}

double eigenvalue = 0.0;
for (int iteration = 0; iteration < maxIterations; iteration++) {
ArrayList<Double> newVector = matrixMultiply(matrix, vector);
double newEigenvalue = vectorNorm(newVector);

// 归一化向量
for (int i = 0; i < n; i++) {
newVector.set(i, newVector.get(i) / newEigenvalue);
}

// Check for convergence
if (Math.abs(newEigenvalue - eigenvalue) < tolerance) {
break;
}

vector = newVector;
eigenvalue = newEigenvalue;
}



return eigenvalue;
}

private static ArrayList<Double> matrixMultiply(ArrayList<ArrayList<Double>> matrix, ArrayList<Double> vector) {
int rows = matrix.size();
ArrayList<Double> result = new ArrayList<>();

for (int i = 0; i < rows; i++) {
double sum = 0.0;
ArrayList<Double> row = matrix.get(i);
for (int j = 0; j < row.size(); j++) {
sum += row.get(j) * vector.get(j);
}
result.add(sum);
}
return result;
}

// Calculate the norm of a vector (L2 norm)
private static double vectorNorm(ArrayList<Double> vector) {
double sum = 0.0;
for (double v : vector) {
sum += v * v;
}
return Math.sqrt(sum);
}




}
Loading