Multithreading
Introduction to Multithreading
A program can be divided into a number of small processes. Each small process can be addressed as a single thread (a lightweight process). Multithreaded programs contain two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. For example, one thread is writing content on a file at the same time another thread is performing spelling check.
In Java, the word thread means two different things.
- An instance of Thread class.
- or, A thread of execution.
An instance of Thread class is just an object, like any other object in java. But a thread of execution means an individual "lightweight" process that has its own call stack. In java each thread has its own call stack.
The main thread
Even if you don't create any thread in your program, a thread called main thread is still created. Although themain thread is automatically created, you can control it by obtaining a reference to it by callingcurrentThread() method.
Two important things to know about main thread are,
- It is the thread from which other threads will be produced.
- main thread must be always the last thread to finish execution.
class MainThread { public static void main(String[] args) { Thread t=Thread.currentThread(); t.setName("MainThread"); System.out.println("Name of thread is "+t); } }
Output :
Name of thread is Thread[MainThread,5,main]
post a comment