Multithreading in java
Multithreading is a mechanism in Java that allows developers to write programs that can perform multiple tasks simultaneously. Here is an example of how to use multithreading in Java:
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + ": " + i);
}
}
}
In this example, we define a Main class that creates two new threads and starts them. We also define a MyRunnable class that implements the Runnable interface and overrides the run method. The run method simply prints a message with the thread ID and a counter.
No comments:
Post a Comment