Skip to content
Open

6 #4

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
Binary file modified .gradle/7.5.1/executionHistory/executionHistory.bin
Binary file not shown.
Binary file modified .gradle/7.5.1/executionHistory/executionHistory.lock
Binary file not shown.
Binary file modified .gradle/7.5.1/fileHashes/fileHashes.bin
Binary file not shown.
Binary file modified .gradle/7.5.1/fileHashes/fileHashes.lock
Binary file not shown.
Binary file modified .gradle/7.5.1/fileHashes/resourceHashesCache.bin
Binary file not shown.
Binary file modified .gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
Binary file modified .gradle/buildOutputCleanup/outputFiles.bin
Binary file not shown.
Binary file modified .gradle/file-system.probe
Binary file not shown.
43 changes: 40 additions & 3 deletions src/main/java/sbu/cs/CPU_Simulator.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ public static class Task implements Runnable {
long processingTime;
String ID;
public Task(String ID, long processingTime) {
// TODO
this.ID = ID;
this.processingTime = processingTime;
}

/*
Expand All @@ -32,7 +33,11 @@ public Task(String ID, long processingTime) {
*/
@Override
public void run() {
// TODO
try {
Thread.sleep(processingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Expand All @@ -44,11 +49,43 @@ Here the CPU selects the next shortest task to run (also known as the
public ArrayList<String> startSimulation(ArrayList<Task> tasks) {
ArrayList<String> executedTasks = new ArrayList<>();

// TODO
while (!tasks.isEmpty()) {
// Find the task with the shortest processing time
Task shortestTask = tasks.get(0);
for (Task task : tasks) {
if (task.processingTime < shortestTask.processingTime) {
shortestTask = task;
}
}

// Remove the shortest task from the list and create a new thread for it
tasks.remove(shortestTask);
Thread thread = new Thread(shortestTask);

// Start the thread, wait for it to finish, and add its ID to the executed tasks list
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
executedTasks.add(shortestTask.ID);
}
return executedTasks;
}

public static void main(String[] args) {

// Create some tasks for testing
ArrayList<Task> tasks = new ArrayList<>();
tasks.add(new Task("Task 1", 3000));
tasks.add(new Task("Task 2", 1000));
tasks.add(new Task("Task 3", 2000));

// Start the simulation and print the list of executed tasks
CPU_Simulator simulator = new CPU_Simulator();
ArrayList<String> executedTasks = simulator.startSimulation(tasks);
System.out.println("Executed tasks: " + executedTasks);

}
}
62 changes: 59 additions & 3 deletions src/main/java/sbu/cs/FindMultiples.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package sbu.cs;

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

/*
In this exercise, you must write a multithreaded program that finds all
integers in the range [1, n] that are divisible by 3, 5, or 7. Return the
Expand All @@ -22,7 +28,7 @@
public class FindMultiples
{

// TODO create the required multithreading class/classes using your preferred method.
private static final int THREAD_POOL_SIZE = 4; // Set the thread pool size as needed


/*
Expand All @@ -32,11 +38,61 @@ public class FindMultiples
public int getSum(int n) {
int sum = 0;

// TODO
Set<Integer> results = new HashSet<>(); // store unique multiples

// Create a thread pool to execute tasks in parallel
ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

// Divide the range [1, n] into smaller chunks to be processed by different threads
int chunkSize = (n + THREAD_POOL_SIZE - 1) / THREAD_POOL_SIZE;
for (int i = 0; i < THREAD_POOL_SIZE; i++) {
int start = i * chunkSize + 1;
int end = Math.min(start + chunkSize - 1, n);
executor.execute(new MultiplesTask(start, end, results));
}

return sum;
// Shutdown the thread pool
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}

for (int multiple : results) {
sum += multiple;
}

return sum;
}

private static class MultiplesTask implements Runnable {
private final int start;
private final int end;
private final Set<Integer> results;

public MultiplesTask(int start, int end, Set<Integer> results) {
this.start = start;
this.end = end;
this.results = results;
}

@Override
public void run() {
for (int i = start; i <= end; i++) {
if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) {
results.add(i);
}
}
}
}

public static void main(String[] args) {

FindMultiples findMultiples = new FindMultiples();
int n = 10;
int sum = findMultiples.getSum(n);
System.out.println("Sum of multiples in the range [1, " + n + "] = " + sum);

}
}
44 changes: 25 additions & 19 deletions src/main/java/sbu/cs/UseInterrupts.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,7 @@

public class UseInterrupts
{
/*
TODO
Analyse the following class and add new code where necessary.
If an object from this type of thread is Interrupted, it must print this:
"{ThreadName} has been interrupted"
And then terminate itself.
*/

public static class SleepThread extends Thread {
int sleepCounter;

Expand All @@ -31,30 +25,28 @@ public SleepThread(int sleepCounter) {
public void run() {
System.out.println(this.getName() + " is Active.");

while (this.sleepCounter > 0)
while (this.sleepCounter > 0 && !Thread.currentThread().isInterrupted())
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

Thread.currentThread().interrupt();
}
finally {
this.sleepCounter--;
System.out.println("Number of sleeps remaining: " + this.sleepCounter);
}
}

if (Thread.currentThread().isInterrupted()) {
System.out.println(this.getName() + " has been interrupted");
}

}
}

/*
TODO
Analyse the following class and add new code where necessary.
If an object from this type of thread is Interrupted, it must print this:
"{ThreadName} has been interrupted"
And then terminate itself.
(Hint: Use the isInterrupted() method)
*/

public static class LoopThread extends Thread {
int value;
public LoopThread(int value) {
Expand All @@ -66,11 +58,15 @@ public LoopThread(int value) {
public void run() {
System.out.println(this.getName() + " is Active.");

for (int i = 0; i < 10; i += 3)
for (int i = 0; i < 10 && !Thread.currentThread().isInterrupted(); i += 3)
{
i -= this.value;

}

if (Thread.currentThread().isInterrupted()) {
System.out.println(this.getName() + " has been interrupted");
}
}
}

Expand All @@ -82,12 +78,22 @@ public static void main(String[] args) {
SleepThread sleepThread = new SleepThread(5);
sleepThread.start();

// TODO Check if this thread runs for longer than 3 seconds (if it does, interrupt it)
try {
Thread.sleep(3000);
sleepThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}

LoopThread loopThread = new LoopThread(3);
loopThread.start();

// TODO Check if this thread runs for longer than 3 seconds (if it does, interrupt it)
try {
Thread.sleep(3000);
loopThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}