OS LAB ASSIGNMENT - 6
Name : Veda Chinta
Registration Number : 23BCE7240
Question 1 : Write a Java Program for Multithreading Using JAVA
Code :
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
System.out.println(threadName + " finished.");
}
}
class MyRunnable implements Runnable {
private String threadName;
MyRunnable(String name) {
threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
System.out.println(threadName + " finished.");
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
Thread t2 = new Thread(new MyRunnable("Thread-2"));
t1.start();
t2.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread - Count: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}
System.out.println("Main Thread finished.");
}
}
Output :
Question 2 : Write a Program for Multithreading Using PTHREADS
Code :
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void* print_message(void* arg) {
char* threadName = (char*) arg;
for (int i = 1; i <= 5; i++) {
printf("%s - Count: %d\n", threadName, i);
sleep(1);
}
printf("%s finished.\n", threadName);
pthread_exit(NULL);
}
int main() {
pthread_t thread1, thread2;
if (pthread_create(&thread1, NULL, print_message, (void*)"Thread-1") != 0) {
perror("Failed to create Thread-1");
exit(1);
}
if (pthread_create(&thread2, NULL, print_message, (void*)"Thread-2") != 0) {
perror("Failed to create Thread-2");
exit(1);
}
for (int i = 1; i <= 5; i++) {
printf("Main Thread - Count: %d\n", i);
sleep(1);
}
printf("Main Thread finished.\n");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Output :