Commit d24d7edd authored by Ali Saeed's avatar Ali Saeed

Upload Homework

parents
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="Threads_Synchronization" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="3b1107cf-8f18-42d0-b9de-b4ed88b26b87" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2YiaBVYwYrdkkXBi0IFFiTryaoB" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"last_opened_file_path": "D:/Lab4/Threads_Synchronization",
"project.structure.last.edited": "Problems",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.2"
}
}]]></component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="3b1107cf-8f18-42d0-b9de-b4ed88b26b87" name="Changes" comment="" />
<created>1701010721222</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1701010721222</updated>
</task>
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Threads_Synchronization</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
package org.example;
public class Main {
public static void main(String[] args) throws Exception {
long timeout = 3000;
ThreadPool threadPool = new ThreadPool(3, 10);
for (int i = 0; i < 60; i++) {
final int taskNo = i;
threadPool.execute(() -> {
String message = Thread.currentThread().getName() + ": Task " + taskNo;
System.out.println(message);
});
}
threadPool.waitUntilAllTasksFinished(timeout);
threadPool.stop();
}
}
\ No newline at end of file
package org.example;
import java.util.LinkedList;
import java.util.Queue;
public class MyBlockingQueue<E> {
private Queue<E> queue;
private int maxNoOfTasks;
public MyBlockingQueue(int maxNoOfTasks) {
queue = new LinkedList<>();
this.maxNoOfTasks = maxNoOfTasks;
}
public synchronized void put(E e) throws InterruptedException {
while ( getQueueSize() == maxNoOfTasks) {
wait();
}
queue.add(e);
notifyAll();
}
public void setQueue(Queue<E> queue) {
this.queue = queue;
}
public void setMaxNoOfTasks(int maxNoOfTasks) {
this.maxNoOfTasks = maxNoOfTasks;
}
public Queue<E> getQueue() {
return queue;
}
public int getMaxNoOfTasks() {
return maxNoOfTasks;
}
public synchronized int getQueueSize() {
return queue.size();
}
public synchronized E take() throws InterruptedException {
while ( getQueueSize() == 0) {
wait();
}
E item = queue.remove();
notifyAll();
return item;
}
}
\ No newline at end of file
package org.example;
public class PoolThreadRunnable implements Runnable {
private Thread thread = null;
private MyBlockingQueue<Runnable> taskQueue = null;
private boolean isStopped = false;
public PoolThreadRunnable(MyBlockingQueue<Runnable> queue) {
taskQueue = queue;
}
public void run() {
this.thread = Thread.currentThread();
while (!isStopped()) {
try {
Runnable runnable = taskQueue.take();
runnable.run();
} catch (Exception e) {
}
}
}
public synchronized void doStop() {
isStopped = true;
this.thread.interrupt();
}
public synchronized boolean isStopped() {
return isStopped;
}
}
\ No newline at end of file
package org.example;
import java.util.ArrayList;
import java.util.List;
public class ThreadPool {
private MyBlockingQueue<Runnable> taskQueue;
private List<PoolThreadRunnable> runnables;
private boolean isStopped;
private int completedTasks;
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
taskQueue = new MyBlockingQueue<>(maxNoOfTasks);
runnables = new ArrayList<>();
isStopped = false;
for (int i = 0; i < noOfThreads; i++) {
PoolThreadRunnable poolThreadRunnable = new PoolThreadRunnable(taskQueue);
runnables.add(poolThreadRunnable);
new Thread(poolThreadRunnable).start();
}
}
public synchronized void execute(Runnable task) throws Exception {
if (isStopped) {
throw new IllegalStateException("ThreadPool is stopped");
}
taskQueue.put(task);
}
public synchronized void stop() {
this.isStopped = true;
for (PoolThreadRunnable runnable : runnables) {
runnable.doStop();
}
}
public void waitUntilAllTasksFinished(long timeout ) {
long startTime = System.currentTimeMillis();
while(this.taskQueue.getQueueSize()>0) {
if (System.currentTimeMillis() - startTime > timeout) {
stop(); // Stop the ThreadPool if timeout is finished
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment