In Java, the term "thread context switching" refers to the process of pausing one thread's execution while starting another. This switching enables multiple threads to work simultaneously and share CPU resources.
The program counter, stack pointers, and other pertinent data for the current thread are stored when a context switch happens. The saved state of another thread is then restored before it is chosen to run and can carry on where it left off with its execution.
Here is a Java example of thread context switching in execution:
class ThreadContextSwitchingExample
{
public static void main(String[] args)
{
// Create two threads
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
// Start both threads
thread1.start();
thread2.start();
}
// Custom Runnable implementation
static class MyRunnable implements Runnable
{
private final String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println(name + " is running");
try {
// Sleep for a short duration to simulate some work
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Output:
Thread 1 is running
Thread 2 is running
Thread 2 is running
Thread 1 is running
Thread 2 is running
Thread 1 is running
Thread 1 is running
Thread 2 is running
Thread 2 is running
Thread 1 is running
Using the MyRunnable class, which implements the Runnable interface, two threads (Thread 1 and Thread 2) are created in the example above.Â
Each thread executes a loop while printing five times the message "is running" and its name.Â
The thread waits for 500 milliseconds in between iterations.
The output from both threads will be interspersed when you run the above program.Â
This interleaving happens as a result of thread context switching, in which the JVM or operating system shifts between the threads to enable concurrent execution.
No comments:
Post a Comment