Commit 6d3fd821 authored by mohammad.salama's avatar mohammad.salama

submit - ThreadPoolProject NOT PoolThreadProject

parent 92c477df
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17 (2)" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ThreadSynchronizing - PP03.iml" filepath="$PROJECT_DIR$/.idea/ThreadSynchronizing - PP03.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
...@@ -3,14 +3,13 @@ ...@@ -3,14 +3,13 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId> <groupId>org.example</groupId>
<artifactId>PersonalThreadPool</artifactId> <artifactId>PersonalThreadPool</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
......
...@@ -6,7 +6,8 @@ public class Main ...@@ -6,7 +6,8 @@ public class Main
for(int i = 0; i < 100; i++) for(int i = 0; i < 100; i++)
{ {
int taskNo = i; int taskNo = i;
myThreadPool.execute(new Runnable() { myThreadPool.execute(new Runnable()
{
@Override @Override
public void run() { public void run() {
String message = Thread.currentThread().getName() + ": Task " + (taskNo + 1) ; String message = Thread.currentThread().getName() + ": Task " + (taskNo + 1) ;
......
...@@ -24,7 +24,7 @@ public class TasksQueue <RunnableType> ...@@ -24,7 +24,7 @@ public class TasksQueue <RunnableType>
synchronized (this) synchronized (this)
{ {
if (!allowInsertion) return; if (!allowInsertion) return;
if (tasks.size() == maxSize) if (this.size() == maxSize)
{ {
///System.out.println("Stuck in Adding"); ///System.out.println("Stuck in Adding");
this.wait(); this.wait();
...@@ -39,13 +39,13 @@ public class TasksQueue <RunnableType> ...@@ -39,13 +39,13 @@ public class TasksQueue <RunnableType>
RunnableType task = null; RunnableType task = null;
synchronized (this) synchronized (this)
{ {
if (tasks.size()==0 && allowInsertion) if (this.size()==0 && allowInsertion)
{ {
///System.out.println("Stuck in Removing"); ///System.out.println("Stuck in Removing");
this.wait(); this.wait();
} }
if (tasks.size() ==0 && !allowInsertion) return task; if (this.size() ==0 && !allowInsertion) return task;
if(tasks.size() == 0) if(this.size() == 0)
{ {
/*System.out.println("HHHHHHHHHHHH"); /*System.out.println("HHHHHHHHHHHH");
System.out.println("!allow" + !allowInsertion);*/ System.out.println("!allow" + !allowInsertion);*/
......
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17 (2)" 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="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ThreadPoolProject.iml" filepath="$PROJECT_DIR$/ThreadPoolProject.iml" />
</modules>
</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="ChangeListManager">
<list default="true" id="8cbae348-bbce-4278-9ba0-e5a0252361d4" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/modules.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/ThreadPoolProject.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/Main.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/MyThreadPool.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/MyThreadPoolRunnable.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/TasksQueue.java" afterDir="false" />
</list>
<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="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="2Yj4r28mhq3xfs9loJx430aOHNu" />
<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",
"last_opened_file_path": "D:/HIAST/FIY/FS/Parallel Programming/Lab/3/HW/PoolThreadProject/ThreadPoolProject/src"
}
}]]></component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="D:\HIAST\FIY\FS\Parallel Programming\Lab\3\HW\PoolThreadProject\ThreadPoolProject\src" />
</key>
</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="8cbae348-bbce-4278-9ba0-e5a0252361d4" name="Changes" comment="" />
<created>1701025849870</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1701025849870</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"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
public class Main
{
public static void main(String[] args) throws Exception
{
MyThreadPool myThreadPool = new MyThreadPool<>(50, 5);
for(int i = 0; i < 100; i++)
{
int taskNo = i;
myThreadPool.execute(new Runnable()
{
@Override
public void run() {
String message = Thread.currentThread().getName() + ": Task " + (taskNo + 1) ;
System.out.println(message);
}
});
}
myThreadPool.waitUntilAllTasksFinished(1000);
myThreadPool.stop();
}
}
\ No newline at end of file
import java.util.ArrayList;
import java.util.List;
public class MyThreadPool <RunnableType extends Runnable>
{
private TasksQueue<RunnableType> tasksQueue;
private List<MyThreadPoolRunnable> workingThreads;
private boolean isTerminated;
private boolean allowInserting;
private int queueSize;
private int workingThreadsNumber;
public MyThreadPool(int queueSizeInput, int workingThreadsNumberInput) throws Exception
{
if (queueSizeInput <=0 || workingThreadsNumberInput <= 0)
{
throw new Exception("Queue Size and Threads Number must be Strictly Larger than zero!!");
}
this.queueSize = queueSizeInput;
this.workingThreadsNumber = workingThreadsNumberInput;
this.isTerminated = false;
this.allowInserting = true;
initiateThreadPool();
startWorking();
}
public void execute (RunnableType runnableType) throws Exception
{
if (isTerminated || !allowInserting) return;
this.tasksQueue.addTask(runnableType);
}
public void stop()
{
synchronized (this)
{
this.isTerminated = true;
this.allowInserting = false;
for (MyThreadPoolRunnable runnable : workingThreads)
runnable.forceStop();
}
}
public synchronized void waitUntilAllTasksFinished(long timeOut) throws InterruptedException
{
if (this.isTerminated) return;
allowInserting = false;
this.isTerminated = true;
tasksQueue.softFinish(timeOut);
}
private void initiateThreadPool()
{
this.tasksQueue = new TasksQueue<>(this.queueSize);
this.workingThreads = new ArrayList<>();
for (int i=1 ; i<= this.workingThreadsNumber ; i++)
{
workingThreads.add(new MyThreadPoolRunnable(tasksQueue));
}
}
private void startWorking()
{
for (MyThreadPoolRunnable myThreadPoolRunnable : workingThreads)
new Thread(myThreadPoolRunnable).start();
}
}
public class MyThreadPoolRunnable<RunnableType extends Runnable> implements Runnable
{
private TasksQueue<RunnableType> tasksQueue;
private boolean isTerminated;
private Thread thread;
public MyThreadPoolRunnable(TasksQueue<RunnableType> tasksQueue)
{
this.tasksQueue = tasksQueue;
this.isTerminated = false;
}
public void forceStop()
{
this.isTerminated = true;
this.thread.interrupt();
}
@Override
public void run()
{
thread = Thread.currentThread();
while(!terminated())
{
try
{
RunnableType job = tasksQueue.removeTask();
if (job == null) continue;
job.run();
}
catch (InterruptedException e)
{
//ignore
}
}
}
private synchronized boolean terminated()
{
return this.isTerminated;
}
}
import java.util.ArrayList;
import java.util.List;
public class TasksQueue <RunnableType>
{
private List<RunnableType> tasks;
private int maxSize;
private boolean allowInsertion;
public TasksQueue(int maxCap)
{
this.maxSize = maxCap;
tasks = new ArrayList<>();
allowInsertion = true;
}
public void addTask(RunnableType task) throws Exception
{
if (task == null)
{
throw new Exception("Task Assigned is NULL");
}
synchronized (this)
{
if (!allowInsertion) return;
while (this.size() == maxSize)
{
///System.out.println("Stuck in Adding");
this.wait();
}
tasks.add(task);
this.notifyAll();
}
}
public RunnableType removeTask () throws InterruptedException
{
RunnableType task = null;
synchronized (this)
{
while (this.size()==0 && allowInsertion)
{
///System.out.println("Stuck in Removing");
this.wait();
}
if (this.size()==0 && !allowInsertion)
{
return task;
}
task = tasks.remove(0);
this.notifyAll();
}
return task;
}
public void softFinish(long timeOut) throws InterruptedException
{
allowInsertion = false;
while (this.size() > 0)
{
Thread.sleep(timeOut);
}
}
private synchronized int size()
{
return tasks.size();
}
}
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