JAVA REGION

Multithreaded Programming

Introduction:

A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each thread defines
a separate path of execution.Thus, multithreading is a specialized form of multitasking.

Multitasking threads require less overhead than multitasking processes. Processes are
heavyweight tasks that require their own separate address spaces. Inter process communication
is expensive and limited. Context switching from one process to another is also costly. Threads,
on the other hand, are lightweight. They share the same address space and cooperatively
share the same heavyweight process. Inter thread communication is inexpensive, and context
switching from one thread to the next is low cost

Why Multithreading in java.?

While Java programs make use of process based
multitasking environments, process-based multitasking is not under the control of
Java. However, multithreaded multitasking is.

 The Main Thread:

When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of your program, because it is the one that is executed when your
program begins. The main thread is important for two reasons:

  • It is the thread from which other “child” threads will be spawned.
  • Often, it must be the last thread to finish execution because it performs various
    shutdown actions.


public class Test1 {

    public static void main(String[] args) {
        Thread thread = Thread.currentThread();
        System.out.println(thread);
        thread.setName("my thread");
        System.out.println(thread);
        for (int i = 0; i < 10; i++) {
            System.out.println(i);

            try {
                thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}

output:

Thread[main,5,main]
Thread[my thread,5,main]
0
1
2
3
4
5
6
7
8

Download this code here

2 comments

gud.....

Reply

oooppppssss

Reply

Post a Comment