About
package prac3; public class threadexample { private static final int LIMIT = 10_000_000; private static final int NUM_THREADS = 4;
public static void main(String[] args) throws InterruptedException {
PrimeThread[] threads = new PrimeThread[NUM_THREADS];
int segmentSize = LIMIT / NUM_THREADS;
int start = 2;
int end = segmentSize;
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new PrimeThread(start, end);
start = end + 1;
end += segmentSize;
}
for (PrimeThread thread : threads) {
thread.start();
}
for (PrimeThread thread : threads) {
thread.join();
}
long sum = 0;
for (PrimeThread thread : threads) {
sum += thread.getSum();
}
System.out.println("Sum of prime numbers up to " + LIMIT + ": " + sum);
}
}
class PrimeThread extends Thread { private final int start; private final int end; private long sum;
PrimeThread(int start, int end) {
this.start = start;
this.end = end;
this.sum = 0;
}
public long getSum() {
return sum;
}
public void run() {
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
sum += i;
}
}
}
private boolean isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
} }
-----------------------------------------------------account without syn---------------------------------------------
import java.util.concurrent.*; public class AccountWithoutSync { private static Account account = new Account();
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); //create executor
// Create and launch 100 threads for (int i = 0; i < 10; i++) { executor.execute(new AddAPennyTask()); //submit task }
executor.shutdown(); //shut down executor
// Wait until all tasks are finished while (!executor.isTerminated()) { //wait for all tasks to //terminate }
System.out.println("What is balance? " + account.getBalance()); }
// A thread for adding a penny to the account private static class AddAPennyTask implements Runnable { public void run() { account.deposit(1); } }
// An inner class for account private static class Account { private int balance = 0;
public int getBalance() { return balance; }
public void deposit(int amount) { int newBalance = balance + amount;
// This delay is deliberately added to magnify the // data-corruption problem and make it easy to see. try { Thread.sleep(5); } catch (InterruptedException ex) { }
balance = newBalance; System.out.println("newBalance is:"+newBalance); } } }
-----------------------------------------sum of 1 to 100 using 4 threads----------------------------------------------------------------- class summ implements Runnable{ private long start; private long end; public long summation;
public summ(long start,long end){
this.start=start;
this.end=end;
}
public void run(){
long summation=0;
for(long i=start;i<=end;i++){
summation=summation+i;
}
this.summation= summation;
}
}
public class Mainn { public static void main(String[] args){
summ s1=new summ(0,25);
summ s2=new summ(26,50);
summ s3=new summ(51,75);
summ s4=new summ(76,100);
Thread t1=new Thread(s1);
Thread t2=new Thread(s2);
Thread t3=new Thread(s3);
Thread t4=new Thread(s4);
t1.start();
t2.start();
t3.start();
t4.start();
try{
t1.join();
}catch(InterruptedException e){
System.out.print("error");
}
try{
t2.join();
}catch(InterruptedException e){
System.out.print("error");
}
try{
t3.join();
}catch(InterruptedException e){
System.out.print("error");
}
try{
t4.join();
}catch(InterruptedException e){
System.out.print("error");
}
long summation=s1.summation+s2.summation+s3.summation+s4.summation;
System.out.print("sum of prime numbers: ");
System.out.print(summation);
} } -------------------------------------------------joint acc by 3 people------------------------------------------ import java.util.concurrent.*; class jointacc{ private int balance; public jointacc(int balance){ this.balance=balance; } public synchronized void deposit(int x){ this.balance=balance+x; } public synchronized void enquire(String name){ System.out.println(this.balance + name); } }
class cust implements Runnable{ private jointacc acc; private String name; private int depo; public cust(String name,int depo,jointacc acc){ this.name=name; this.depo=depo; this.acc=acc; } public void run(){ acc.deposit(this.depo); acc.enquire(this.name); }
}
class bank{ public static void main(String[] args){ jointacc acc = new jointacc(100); cust c1=new cust("yash",100,acc); cust c2=new cust("sash",200,acc); cust c3=new cust("hash",300,acc);
// ExecutorService executor=Executors.newCachedThreadPool();
ExecutorService executor=Executors.newFixedThreadPool(4);
executor.execute(c1);
executor.execute(c2);
executor.execute(c3);
executor.shutdown();
} }
......................................................... Bubble sort
import java.util.Arrays;
class BubbleSortThread extends Thread { private int[] arr;
public BubbleSortThread(int[] arr) {
this.arr = arr;
}
public void run() {
bubbleSort(arr);
}
private void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
private synchronized void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
class MergeThread extends Thread { private int[][] subArrays; private int[] mergedArray;
public MergeThread(int[][] subArrays, int[] mergedArray) {
this.subArrays = subArrays;
this.mergedArray = mergedArray;
}
public void run() {
mergeSortedArrays(subArrays, mergedArray);
}
private void mergeSortedArrays(int[][] subArrays, int[] mergedArray) {
int totalLength = mergedArray.length;
int[] indexes = new int[subArrays.length];
Arrays.fill(indexes, 0);
for (int i = 0; i < totalLength; i++) {
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for (int j = 0; j < subArrays.length; j++) {
int index = indexes[j];
if (index < subArrays[j].length && subArrays[j][index] < minValue) {
minValue = subArrays[j][index];
minIndex = j;
}
}
mergedArray[i] = minValue;
indexes[minIndex]++;
}
}
}
public class ParallelBubbleSort { public static void main(String[] args) throws InterruptedException { int[] arr = generateArray(40000);
// Sequential Bubble Sort
int[] arrSequential = arr.clone();
long startTimeSequential = System.currentTimeMillis();
bubbleSort(arrSequential);
long endTimeSequential = System.currentTimeMillis();
long sequentialTime = endTimeSequential - startTimeSequential;
// Parallel Bubble Sort
int numThreads = 4;
int[] arrParallel = arr.clone();
int[][] subArrays = splitArray(arrParallel, numThreads);
long startTimeParallel = System.currentTimeMillis();
BubbleSortThread[] threads = new BubbleSortThread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new BubbleSortThread(subArrays[i]);
threads[i].start();
}
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
int[] mergedArray = new int[arrParallel.length];
MergeThread mergeThread = new MergeThread(subArrays, mergedArray);
mergeThread.start();
mergeThread.join();
long endTimeParallel = System.currentTimeMillis();
long parallelTime = endTimeParallel - startTimeParallel;
System.out.println("Sequential Bubble Sort Time: " + sequentialTime + "ms");
System.out.println("Parallel Bubble Sort Time: " + parallelTime + "ms");
}
private static int[] generateArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = (int) (Math.random() * size);
}
return arr;
}
private static int[][] splitArray(int[] arr, int numParts) {
int[][] subArrays = new int[numParts][];
int length = arr.length / numParts;
for (int i = 0; i < numParts; i++) {
if (i == numParts - 1) {
subArrays[i] = Arrays.copyOfRange(arr, i * length, arr.length);
} else {
subArrays[i] = Arrays.copyOfRange(arr, i * length, (i + 1) * length);
}
}
return subArrays;
}
private static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}