Commit 8045b208 authored by ahmad.abdulla's avatar ahmad.abdulla

third Homework"

parent 7ffe0998
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ 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="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="4cb1fdde-cf4f-4cd2-b2d7-8c1392620aa8" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/encodings.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.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$/pom.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/Main.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="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="2Yi4utNMSPcdDwcbhfSahyFr4uo" />
<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",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.0"
}
}]]></component>
<component name="RunManager" selected="Application.Main">
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.example.Main" />
<module name="Ahmad_HW3" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="RaceConditionExample" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.example.RaceConditionExample" />
<module name="Ahmad_HW3" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.RaceConditionExample" />
</list>
</recent_temporary>
</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="4cb1fdde-cf4f-4cd2-b2d7-8c1392620aa8" name="Changes" comment="" />
<created>1700995310692</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1700995310692</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>Ahmad_HW3</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<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) {
ThreadPool threadPool = new ThreadPool(3, 10);
for (int i = 0; i < 10; i++) {
int taskNo = i;
try {
threadPool.execute(() -> {
String message = Thread.currentThread().getName() + ": Task " + taskNo;
System.out.println(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Wait for all tasks to finish or timeout after 5 seconds
threadPool.waitUntilAllTasksFinished(5000);
// Stop the thread pool
threadPool.stop();
}
}
\ No newline at end of file
package org.example;
class PoolThreadRunnable implements Runnable {
private Thread thread;
private ThreadPool threadPool;
private boolean isStopped;
public PoolThreadRunnable(ThreadPool threadPool) {
this.threadPool = threadPool;
isStopped = false;
}
public void run() {
thread = Thread.currentThread();
while (!isStopped()) {
try {
Runnable task = threadPool.getTask();
if (task == null) {
break; // Exit the loop when there are no more tasks
}
task.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean isStopped() {
return isStopped;
}
}
package org.example;
import java.util.ArrayList;
import java.util.List;
public class ThreadPool {
private List<PoolThreadRunnable> runnables;
private List<Runnable> taskQueue;
private boolean isStopped;
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
runnables = new ArrayList<>(noOfThreads);
taskQueue = new ArrayList<>(maxNoOfTasks);
isStopped = false;
for (int i = 0; i < noOfThreads; i++) {
PoolThreadRunnable poolThreadRunnable = new PoolThreadRunnable(this);
runnables.add(poolThreadRunnable);
new Thread(poolThreadRunnable).start();
}
}
public void execute(Runnable task) {
synchronized (taskQueue) {
taskQueue.add(task);
taskQueue.notify();
}
}
public void waitUntilAllTasksFinished(long timeoutMillis) {
long startTime = System.currentTimeMillis();
long elapsedTime=0;
synchronized (taskQueue) {
while (!taskQueue.isEmpty()) {
try {
taskQueue.wait(timeoutMillis);
} catch (InterruptedException e) {
// Handle the exception
e.printStackTrace();
}
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("elapsedTime is :" + elapsedTime);
System.out.println("timeoutMillis is :" + timeoutMillis);
if (elapsedTime >= timeoutMillis) {
break;
}
}
}
}
public void stop() {
synchronized (taskQueue) {
isStopped = true;
taskQueue.notifyAll();
}
}
public boolean isStopped() {
return isStopped;
}
protected Runnable getTask() throws InterruptedException {
synchronized (taskQueue) {
while (taskQueue.isEmpty() && !isStopped) {
taskQueue.wait(); // Wait until a task is available or the thread pool is stopped
}
if (isStopped) {
return null; // Return null to indicate that the thread should stop
} else {
return taskQueue.remove(0);
}
}
}
}
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