#include <stdio.
h>
#include <pthread.h>
// Thread function definition
void* threadFunction(void* args) {
printf("I am a thread function.\n");
return NULL; // Thread functions should return void*
}
int main() {
// Creating thread ID
pthread_t id;
int ret;
// Creating thread
ret = pthread_create(&id, NULL, &threadFunction, NULL);
if (ret == 0) {
printf("Thread created successfully.\n");
} else {
printf("Thread not created.\n");
return 1; // Return error code
}
// Wait for the thread to finish (optional)
pthread_join(id, NULL);
printf("I am main function.\n");
return 0;
}
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
// public class SingleThreadExample {
// public static void main(String[] args) {
// [Link]("Main thread: " + [Link]().getName());
// for (int i = 1; i <= 3; i++) {
// [Link]("Task " + i + " (main thread)");
// }
// }
// }
public class MultiThreadExample {
public static void main(String[] args) {
// Create two threads
Thread thread1 = new Thread(new Task("Thread-1"));
Thread thread2 = new Thread(new Task("Thread-2"));
// Start threads (calls run() method)
[Link]();
[Link]();
[Link]("Main thread: " + [Link]().getName());
}
static class Task implements Runnable {
private String name;
public Task(String name) {
[Link] = name;
}
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](name + ": Task " + i);
try {
[Link](100); // Simulate work
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
// Example 2: [Link]
public class RunnableTest {
public static void main(String[] args) {
RunCounter rct = new RunCounter(); // Step 1: Create a Runnable
object
Thread th = new Thread(rct); // Step 2: Pass it to a Thread
object
[Link](); // Step 3: Start the thread
[Link]("The thread has been started"); // Main thread message
}
}
// A class that implements Runnable
class RunCounter implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Running count: " + i);
try {
[Link](500); // Pause for 500 milliseconds (optional, for
demo)
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}