Java thread Introduction

Source: Internet
Author: User

In java, a Thread is represented by a Thread object.
Generally, every java program has a main method (not an applet), which is the entry point of the main thread.
For a Thread, the entry point is not main, but the run method.
Define a thread, mainly to write its run Method
There are two methods to write run. One is to inherit the Thread class and then override its run
The other is to implement the Runnable interface, and then rewrite its run, as shown below:
======================================
// Use external classes to implement Multithreading
Class ThreadTest2
{
Public static void main (String [] args)
{
New ThreadTest2 ();
}
ThreadTest2 (){
For (int I = 1; I <= 5; I ++ ){
System. out. println ("creating thread" + I );
OutterThread th = new outterThread (I); // create a new thread
Th. start (); // start the newly created thread
}
}
}

Class outterThread extends Thread // implement multithreading by inheriting the Thread class; External class
{
Int count;
OutterThread (int I ){
Count = I;
}
Public void run (){
While (true ){
System. out. println ("thread" + count + "is running ");
Try {
Sleep (1000 * count );
}
Catch (InterruptedException e ){}
}
}
}
============================================
Class ThreadTest3 implements Runnable // implement multithreading through the Runnable interface
{
Int count;
Public static void main (String [] args)
{
For (int I = 1; I <= 5; I ++)
// Call the constructor Thread (Runnable target) of the Thread class)
New Thread (new ThreadTest3 (I). start ();
}
ThreadTest3 (int I ){
System. out. println ("creating thread" + I );
Count = I;
}
Public void run (){
While (true ){
System. out. println ("thread" + count + "is running ");
Try {
Thread. sleep (1000 * count); // sleep the Thread for a period of time
}
Catch (InterruptedException e ){}
}
}
}
We can see that the Thread object is generated no matter how run is rewritten. The difference is that the second method should pass the Runnable implementation class in the Thread constructor as the parameter.
In the preceding example, start () and sleep () are used ()
The former is used as the startup thread. After calling it, the run method starts to be executed. The latter causes the thread to pause the specified time, in milliseconds. this sleep throws an exception, so try and catch blocks are required.
======================================
In the preceding example, the threads created in the for loop are parallel with the main thread. The end of one thread does not affect the end of another thread.
In the above example, after the for loop is executed, the main thread ends, while other threads are still running
SetDaemon () can be used to execute a thread as a background thread. That is to say, when other non-Daemon threads end, the background thread will exit no matter whether the run is finished or not.
In turn, you can also make the main thread wait for other threads to end before exiting. note that the main thread waits for the end of other threads, and the daemon thread mentioned above exits after all non-daemon (main thread and other non-daemon. to achieve this, you can use join (). it can contain parameters or not. If a parameter is used, the parameter indicates the waiting time. If the specified time expires, no matter whether the join thread exits or not, the main thread ends (if the main method has been executed)
The following is an example
======================================
Class DaemonAndJoin
{
Public static void main (String [] args)
{
Thread th = new Thread (new Runnable (){
Int count = 2;
Public void run (){
While (count> 0 ){
For (int I = 0; I <5; I ++ ){
Try {
Thread. sleep (500 );
System. out. println ("in thread 1 ");
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
Count --;
System. out. println ("one for is done ");
}
}
});
Thread Th1 = new Thread (new Runnable (){
Public void run (){
While (true ){
Try {
Thread. sleep (1000 );
System. out. println ("in thread 2 ");
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
});
System. out. println ("main thread begins ");
Th. start ();
Th2.setDaemon (true); // sets the background thread
Th2.start ();
Try {
Th. join (); // join
} Catch (InterruptedException e ){
E. printStackTrace ();
}
System. Out. println ("main thread quits ");
}
}
====================
In the above example, if the thread TH is not present, the master thread and the master thread will soon end.
If there is th, but there is no join, the main thread will soon end, but because there is another non-daemon, it will not end soon, and it will not end until th ends.
If no setdaemon exists, th does not affect
============================
Thread Synchronization
When multiple threads operate on an object at the same time, a problem may occur. At this time, thread synchronization is required to solve the problem.
Consider the following example:
Class sychronizedtest
{
Public static void main (string [] ARGs)
{
Final student Stu = new student ();
Thread setnameandnumth1 = new thread (New runnable (){
Public void run (){
While (true ){
Synchronized (Stu ){
Stu. setNameAndNum ("john", "jj ");
}
}
}
});
Thread setnameandnumh2 = new Thread (new Runnable (){
Public void run (){
While (true ){
// Synchronized (stu ){
Stu. setNameAndNum ("kate", "kk ");
//}
}
}
});
SetNameAndNumth1.start ();
SetNameAndNumth2.start ();
System. out. println ("test started :");
}
}
Class Student {
Private String name;
Private String id;
Private int count = 0;
Public/* synchronized */void setNameAndNum (String name, String id ){
// Synchronized (this ){
This. name = name;
This. id = id;
Count ++;
If (! Check ())
System. out. println (count + "unmatched name and id:" + name + "" + id );
//}
}
Private boolean check (){
Return name. charAt (0) = id. charAt (0 );
}
}
In this example, the Student class has two attributes.
There are two threads that modify the instance of the same Student class, and then check whether the two attribute characters of the modified instance do not meet the requirements (determine whether the first character of the two attributes is the same)
If not, the statement is output on the console. Otherwise, the statement is not output.
There are three annotations in this example. Each part describes a synchronization method.
The above method enables student class methods to be executed in synchronous mode.
The second is to use the synchronized keyword to make a single method, instead of executing all methods in synchronous mode.
The third method is to execute a part of a method in the synchronous method (although in this example, the entire method is included)
==========================================
The classic consumer program is attached.
Class waitpolicytest
{
Public static void main (string [] ARGs)
{
Clerk = new clerk ();
Producer producer = new producer (clerk );
Consumer consumer = new consumer (clerk );
Thread producerthread = new thread (producer );
Thread consumerthread = new thread (consumer );
Producerthread. Start ();
Consumerthread. Start ();
}
}
Class producer implements runnable {
Clerk;
Producer (clerk ){
This. Clerk = clerk;
}
Public void run (){
System. Out. println ("producer starts producing product ");
For (INT I = 0; I <10; I ++ ){
Try {
Thread. Sleep (INT) (math. Random () * 3000 ));
} Catch (interruptedexception e ){
E. printstacktrace ();
}
Clerk. setproduct (I );
// System. Out. println ("producer is producing product" + I );

}
}
}
Class consumer implements runnable {
Clerk;
Consumer (Clerk clerk ){
This. clerk = clerk;
}
Public void run (){
System. out. println ("consumer starts consuming product ");
For (int I = 0; I <10; I ++ ){
Try {
Thread. sleep (int) (Math. random () * 3000 ));
} Catch (InterruptedException e ){
E. printStackTrace ();
}
Clerk. getProduct ();
// System. out. println ("consumer is consuming product" + I );

}
}
}
Class Clerk {
Int product =-1;
Public synchronized void setProduct (int product ){
If (this. product! =-1 ){
Try {
Wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
This. product = product;
System. out. println ("producer is producing product" + product );
Notify ();
}
Public synchronized void getProduct (){
If (product =-1 ){
Try {
Wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
System. Out. println ("consumer is consuming product" + product );
This. Product =-1;
Notify ();
}
}

Related Article

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.