Java multithreading Basics

Source: Internet
Author: User

Java multithreading Basics

A thread is a major feature of Java. It can be a given sequence of commands, variables defined in a given method, or shared data (Class-level variables ). In Java, each thread has its own stack and program counter (PC), where the stack is used to track the context of the thread (the context is when the thread is executed somewhere, the value of the current local variable), and the program counter is used to track the commands being executed by the current thread.
  
In general, a thread cannot access the stack variable of another thread, and the thread must be in one of the following states:
  
1. the queue status (Ready). After a user creates a thread, this thread does not run immediately. When the method start () in the thread is called, the thread will queue and wait for the scheduler to transfer it to the Running state (Running ). After a process is executed, it can also be queued. If the scheduler permits this, you can call the yield () method to put the process in a queue.
  
2. Running status (Running). When the scheduler allocates the CPU Running time to a thread, the thread enters the Running status and starts Running.
  
3. The Waiting state (Waiting) may cause the thread to be in the Waiting state for many reasons, such as being paused during thread execution or Waiting for the completion of the I/O request to enter the Waiting state.
  
Different threads in Java have different priorities. High-priority threads can be completed before low-priority threads. If multiple threads have the same priority, Java switches between different threads. An application can set the thread priority by using the method setPriority () in the thread, and use the method getPriority () to obtain the priority of a thread.
  
Life cycle of one thread
  
The life cycle of a thread can be divided into two stages: Alive and Dead. The life cycle includes Running and Waiting ). After a new thread is created, the thread enters the queuing status (Ready). When the method start () in the thread is called, the thread enters the lifecycle, at this time, its method isAlive () always returns the true value until the thread enters the dead state.
  
Implementation of two threads
  
There are two ways to implement the Thread, one is to extend the java. lang. Thread class, and the other is through the java. lang. Runnable interface.
  
The Thread class encapsulates the Thread behavior. To create a Thread, you must create a new class extended from the Thread class. Because the method run () in the Thread class does not provide any operations, the user must overwrite the method run () to complete useful work when creating the Thread. When the start () method in the thread is called, The run () method is called again. The following code is to implement the Thread by extending the Thread class:

Package simple;

Import java. awt .*;

Class Sample1 {

Public static void main (String [] args ){

Mythread test1 = new Mythread (1 );

Mythread test2 = new Mythread (2 );

Test1.start ();

Test2.start ();

}

}

Class Mythread extends Thread {

Int id;

Mythread (int I)

{Id = I ;}

Public void run (){

While (id = 1 ){

Try {sleep (1000 );

}
Catch (InterruptedException e ){}

}

System. out. println ("The id is" + id );

}
}

Generally, when you want a class to run in your own thread and expand the special names of some other classes, you need to run the Runnable interface. The Runnable interface has only one method run (). Whenever a class using the Runnable interface is created, you must write the run () method in the class to overwrite the run () method in the interface. For example, the following code is a thread implemented through the Runnable interface:
Package simple;

Import java. applet. Applet;

Public class Bounce extends Applet implements Runnable {

Static int r = 30;

Static int x = 100;

Static int y = 30;

Thread t;

Public void init ()

{

T = new Thread (this );

T. start ();

}

Public void run ()

{

Int Y1 = + 1;

Int sleeptime = 1000;

While (true)

{

Y1 =-Y1;

System. Out. println ("Y1:" + Y1 );

Try {

T. Sleep (sleeptime );

}
Catch (interruptedexception e ){}

}

}

}

The following program uses the two multithreading methods above, which may seem more clear and memorable!

Package simple;
Import java. Io .*;
Import java.net .*;

Public class both
{
Public static void main (string ARGs [])
{
Final string urlstring = ARGs [0];
Final string message = ARGs [1];
Thread thread1 = new thread (){
Public void run ()
{
While (true)
{
Try
{

URL url = new URL (urlstring );
Urlconnection connection = URL. openconnection ();
Inputstreamreader ISR = new inputstreamreader (connection. getinputstream ());
Bufferedreader reader = new bufferedreader (ISR );
Int COUNT = 0;
While (reader. Read ()! =-1)
{
Count ++;
}
System. out. println ("Size is:" + count );
Reader. close ();

Thread. sleep (1000 );
}
Catch (MalformedURLException e)
{
System. err. println ("Bad URL:" + urlString );
}
Catch (IOException e)
{
System. err. println ("I/O Problems ");
}
Catch (InterruptedException e)
{
}

}
}
};

Thread1.start ();

Runnable runnable = new Runnable ()
{
Public void run ()
{
While (true)
{
System. out. println (message );
Try
{
Thread. sleep (500 );
}
Catch (interruptedexception E)
{
}
}
}
};
Thread thread2 = new thread (runnable );
Thread2.start ();

Try {
System. Out. println ("press enter to stop ");
System. In. Read (New byte [10]);
} Catch (ioexception E)
{
System. Out. println ("I/O problems ");
}

System. Exit (0 );
}
}

Effect after execution:

3. Thread Pool

In Java, if a new thread is created every time a request arrives, the overhead is considerable. In actual use, the time and system resources consumed by the server that creates a new thread for each request during thread creation and destruction, it may even take much more time and resources than processing actual user requests. In addition to the overhead of creating and destroying threads, active threads also consume system resources. If too many threads are created in a JVM, the system resources may be insufficient due to excessive memory consumption or excessive switching. To prevent resource insufficiency, server applications need some methods to limit the number of requests processed at any given time point and minimize the number of threads created and destroyed, in particular, the creation and destruction of some threads that consume a large amount of resources should try to use existing objects for service. This is why the "pooled resources" Technology is created.
  
The thread pool is mainly used to solve the thread lifecycle overhead and resource insufficiency issues. By reusing threads for multiple tasks, the overhead created by the thread is apportioned to multiple tasks, and because the thread already exists when the request arrives, this eliminates the latency caused by thread creation. In this way, the application can immediately respond to the request. In addition, adjust the number of threads in the thread pool appropriately to prevent resource insufficiency.
   
A relatively simple thread pool should contain at least the thread pool manager, working thread, task queue, task interface, and so on. The thread pool manager is used to create, destroy, and manage the thread pool, and put the worker thread into the thread pool. The worker thread is a thread that can execute tasks cyclically, wait when there are no tasks. The function of the task queue is to provide a buffer mechanism to put unprocessed tasks in the task queue. The task interface is a required interface for each task, it is mainly used to specify the entry of a task, the finishing work after the task is executed, and the execution status of the task. The worker thread schedules the task execution through this interface.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.