Java Technology topic Review Threads (1)

Source: Internet
Author: User
Tags xquery

This article provides a detailed overview of the Java technology topics in the threaded article


The methods that are often used to write programs with multithreaded capabilities are:


Run (), start (), Wait (), notify (), Notifyall (), sleep (), yield (), join ()


There is also an important keyword: synchronized


This article will explain the above content.


A: Run () and start ()


Example 1:

public cla ThreadTest extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.print(" " + i);
}
}
public static void main(String[] args)
{
new ThreadTest().start();
new ThreadTest().start();
}
}


This is a simple multithreaded program. Run () and start () are two ways that everyone is familiar with. The code that wants to work in parallel is placed in run () and stat () is used to automatically call run (), which is defined by the inherent mechanism of java. and the access control for run () must be public, the return value must be void (this is inaccurate, run () has no return value), and run () takes no parameters.


These rules must have been known to all, but do you know why the Run method has to be declared in this form? This involves Java's approach to overriding and overloading the rules. This content is important, please refer to the relevant information.


Two: keyword synchronized


With the Synchronized keyword, the results of the multi-threaded function will become controllable. The Synchronized keyword is used to protect shared data. Please note that "shared data", you must distinguish between what data is shared data, Java is an object-oriented programming language, so beginners in the programming of multi-threaded programs, it is easy to tell which data is shared data. Take a look at the following example:


Example 2:

public cla ThreadTest implements Ruable
{
public synchronized void run()
{
for(int i=0;i<10;i++)
{
System.out.print(" " + i);
}
}
public static void main(String[] args)
{
Ruable r1 = new ThreadTest();
Ruable r2 = new ThreadTest();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}


In this program, run () is added with the Synchronized keyword. Two threads were created in the main method. You may think that the results of this program must be: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9. But you were wrong! The Synchronized keyword in this program does not protect the shared data (in fact, in this program the Synchronized keyword does not play any role, the results of this program can not be predetermined). The T1,T2 in this program is a thread of two objects (R1,R2). Java is an object-oriented programming language, the data of different objects is different, R1,R2 has its own run () method, and synchronized makes multiple threads of the same object, at some point only one of the threads can access the object's synchronized data. Each object has a "lock flag", and when a thread of this object accesses one of the object's synchronized data, all the synchronized-modified data for that object is locked (because the "lock flag" is taken away by the current thread), The current thread frees the "lock flag" only if the front-end accesses the synchronized data it wants to access, so that other threads of the same object have access to the synchronized data.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


Example 3:

public cla ThreadTest implements Ruable
{
public synchronized void run()
{
for(int i=0;i<10;i++)
{
System.out.print(" " + i);
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}


If you run this program 1000 times, its output must always be: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9. Because the synchronized here protect the shared data. T1,T2 is two threads of the same object (R), when one of the threads (for example: T1) starts executing the run () method, because run () is protected by synchronized, Therefore, other threads of the same object (T2) cannot access the Synchronized method (Run method). Only after T1 executes T2 will the opportunity be executed.


Example 4:

public cla ThreadTest implements Ruable
{
public void run()
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.print(" " + i);
}
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}


This program is the same as the result of example 3. Where possible, the scope of protection should be minimized, in the form of Example 4, this represents "this object". There is no need to protect the entire run (), the Code in Run () has only one for loop, so just protect the for loop.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


Example 5:

Public CLA ThreadTest implements Ruable
{
public void Run ()
{
for (int k=0;k<5;k++)
{
System.out.println (Thread.CurrentThread (). GetName ()
+ ": For loop:" + K);
}
Synchronized (This)
{
for (int k=0;k<5;k++)
{
System.out.println (Thread.CurrentThread (). GetName ()
+ ": Synchronized for Loop:" + K);
}
}
}
public static void Main (string[] args)
{
ruable r = new ThreadTest ();
thread T1 = new Thread (R, "T1_name");
Thread t2 = new Thread (R, "T2_name");
T1.start ();
T2.start ();
}
}
Running Result: T1_name:for loop:0
T1_name:for loop:1
T1_name:for Loop:2
T2_name:for loop:0
T1_name:for Loop:3
T2_name:for loop:1
T1_name:for Loop:4
T2_name:for Loop:2
T1_name:synchronized for loop:0
T2_name:for Loop:3
T1_name:synchronized for Loop:1
T2_name:for Loop:4
T1_name:synchronized for Loop:2
T1_name:synchronized for Loop:3
T1_name:synchronized for Loop:4
T2_name:synchronized for loop:0
T2_name:synchronized for Loop:1
T2_name:synchronized for Loop:2
T2_name:synchronized for Loop:3
T2_name:synchronized for Loop:4


The first for loop is not protected by a synchronized. For the first for loop, T1,T2 can be accessed at the same time. The result of the operation shows that T2 started executing when T1 was executed to k=2. T1 first executes the first for loop, and the first for loop is not finished (T2 just executed to k=2). T1 starts execution of the second for loop, and when the second for loop of T1 executes to k=1, the first for loop of T2 is done. T2 wants to start the second for loop, but since T1 executes the second for loop first, the lock flag of the object is naturally in the hands of the T1 (the Synchronized method's execution also falls into the T1 hands), it will not release the lock flag when the second for loop is not executed by T1. So T2 must wait until T1 executes the second for loop before it can execute a second for loop.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


Three: Sleep ()


Example 6:

public cla ThreadTest implements Ruable
{
public void run()
{
for(int k=0;k<5;k++)
{
if(k == 2)
{
try
{
Thread.currentThread().sleep(5000);
}
catch(Exception e)
{}
}
System.out.print(" " + k);
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t = new Thread(r);
t.start();
}
}


The Sleep method suspends the current thread for a certain amount of time (running opportunities for other threads). Readers can run example 6 to see what the results are. The Sleep method throws an exception and must provide the capture code.


Example 7:

public cla ThreadTest implements Ruable
{
public void run()
{
for(int k=0;k<5;k++)
{
if(k == 2)
{
try
{
Thread.currentThread().sleep(5000);
}
catch(Exception e)
{}
}
System.out.println(Thread.currentThread().getName()
+ " : " + k);
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r,"t1_name");
Thread t2 = new Thread(r,"t2_name");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}


The T1 is set to the highest priority, and the T2 is set to the lowest priority level. T1 do not finish, T2 will not have the opportunity to execute. But because T1 in the middle of the execution of the break for 5 seconds, which makes T2 have the opportunity to execute. Readers can run the program and try it out.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


Example 8:

public cla ThreadTest implements Ruable
{
public synchronized void run()
{
for(int k=0;k<5;k++)
{
if(k == 2)
{
try
{
Thread.currentThread().sleep(5000);
}
catch(Exception e)
{}
}
System.out.println(Thread.currentThread().getName()
+ " : " + k);
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r,"t1_name");
Thread t2 = new Thread(r,"t2_name");
t1.start();
t2.start();
}
}


The reader is asked to run the sample 8 program first, from the results of the run: When a thread is in sleep, it does not release the lock flag for this object.


IV: Join ()


Example 9:

public cla ThreadTest implements Ruable
{
public static int a = 0;
public void run()
{
for(int k=0;k<5;k++)
{
a = a + 1;
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t = new Thread(r);
t.start();
System.out.println(a);
}
}


is the output of the program 5? The answer is: it's possible. In fact, it is difficult to meet the output 5, usually not 5. This does not explain why the output is not 5, I would like to say: How to make the output of 5! In fact, the join () method provides this functionality. The join () method, which enables the thread that called the method to execute before this is completed.


The main () method of example 9 should look like this:

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article

public static void main(String[] args) throws Exception
{
Ruable r = new ThreadTest();
Thread t = new Thread(r);
t.start();
t.join();
System.out.println(a);
}


At this point, the output must be 5! The join () method throws an exception and the capture code should be provided. Or left to the JDK for capture.


Example 10:

public cla ThreadTest implements Ruable
{
public void run()
{
for(int k=0;k<10;k++)
{
System.out.print(" " + k);
}
}
public static void main(String[] args) throws Exception
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t1.join();
t2.start();
}
}


Run this program to see if the results are the same as example 3?


V: Yield ()


The yield () method is similar to the sleep () method, except that it cannot be paused by a user-specified thread for a long time. According to Sun, the sleep method allows a low-priority thread to be executed and, of course, gives the same priority and high-priority threads the opportunity to execute. The yield () method only enables threads with the same priority to have an opportunity to execute.


Example 11:

public cla ThreadTest implements Ruable
{
public void run()
{
8
for(int k=0;k<10;k++)
{
if(k == 5 &amam Thread.currentThread().getName().equals("t1"))
{
Thread.yield();
}
System.out.println(Thread.currentThread().getName()
+ " : " + k);
}
}
public static void main(String[] args)
{
Ruable r = new ThreadTest();
Thread t1 = new Thread(r,"t1");
Thread t2 = new Thread(r,"t2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
输出结果:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t1 : 4
t1 : 5
t1 : 6
t1 : 7
t1 : 8
t1 : 9
t2 : 0
t2 : 1
t2 : 2
t2 : 3
t2 : 4
t2 : 5
t2 : 6
t2 : 7
t2 : 8
t2 : 9


Run this program multiple times, and the output is the same. This means that the yield () method does not allow threads of different priority to have an opportunity to execute.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


VI: Wait (), notify (), Notifyall ()


First Note: Wait (), notify (), Notifyall () These methods are provided by the Java.lang.Object class, and the methods described above are provided by the Java.lang.Thread class (the thread class implements the Ruable interface).


Wait (), notify (), Notifyall () These three methods are used to coordinate the access of multiple threads to shared data, so you must use these three methods within a synchronized statement block. Let's look at the following example:


Example 12:

public Cla ThreadTest implements Ruable
{
public static int sharevar = 0;
Public synchronized void Run ()
{
if (Sharevar = = 0)
{
for (int i=0;i<10;i++)
{
sharevar++;
if (Sharevar = = 5)
{
Try
{
this.wait ();
}
catch (Exception e)
{}
}
}
}
if (Sharevar! = 0)
{
System.out.print (Thread.CurrentThread (). GetName ());
System.out.println ("Sharevar =" + Sharevar);
This.notify ();
}
}
public static void Main (string[] args)
{
Ruable r = new ThreadTest ();
thread T1 = new Thread (r, "T1");
Ten
Thread t2 = new Thread (r, "T2");
T1.start ();
T2.start ();
}
}
Run Result:
T2 sharevar = 5
T1 Sharevar = ten


The T1 thread executes first. Since the initial state of Sharevar is 0,T1 will cause Sharevar to continuously add 1, when the value of Sharevar is 5 o'clock, T1 calls the Wait () method, T1 will be in a resting state while releasing the lock flag. At this point T2 gets the lock flag to start execution, the value of Sharevar has changed to 5, so T2 directly outputs Sharevar value, and then calls the Notify () method to wake T1. T1 then the progress of the last break to continue execution, the value of Sharevar has been added to 10, because the value of Sharevar at the moment is not 0, so T1 will output the value of Sharevar at the moment, and then call the Notify () method, because there is no waiting for the lock flag thread, Therefore, this call statement does not serve any purpose.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


This program simply demonstrates the use of Wait (), notify (), and the reader needs to continue to explore in practice.


Seven: on the thread supplement


Writing a program with multithreaded capability can inherit the thread class, or implement the Ruable interface. How do you choose between these two methods? From an object-oriented perspective, the author recommends that you implement the Ruable interface. Sometimes you also have to implement ruable interfaces, such as when you write small applications that have multithreading capabilities.


Scheduling of Threads: Newruingruableotherwise blockeddeadblocked in object ' Sit () poolblocked in object ' Slock poolnotify () Schedulercompletesrun () Start () sleep () or join () sleep () timeout or thread join () s or interupt () Lockavailablesynchronized () Thread states


Terupt () A thread object in its life cycle in a variety of different states, vividly illustrate this point. WA in


Calling the start () method causes the thread to be in a running state, which means it can be dispatched and executed by the JVM. This does not mean that the thread will run immediately.


In fact, multiple threads in a program are not executed concurrently. Unless the thread is executing on a real multi-CPU computer system, the thread uses a single CPU that must be executed in turn. However, as this happens quickly, we often assume that these threads are executed concurrently.


The Scheduler scheduler for the Java Runtime system is preemptive. If the scheduler is running a thread and another higher-priority thread comes in, the currently executing thread is temporarily terminated and the higher-priority thread executes.


The Java Scheduler Scheduler does not preempt the current thread for another thread that has the same priority as the current thread. However, although the scheduling scheduler itself does not have a time slice (that is, it does not give the same priority thread to execute the used time slices), the system implementation of threads based on the thread class may support time slice allocation. Depending on the operating system, Windows and UNIX support for this issue will not be exactly the same.

Keyword: DbUnit unit test process Continuous Integration Maven XQuery dynamic compilation

This article provides a detailed overview of the Java technology topics in the threaded article


Since you are not sure what operating system the applet will run on, you should not write a program that relies on time-slice allocation. That is, the yield method should be used to allow threads of the same priority to have the opportunity to execute instead of expecting each thread to automatically get a slice of CPU time.


The thread class provides a mechanism for you to process threads that are not related to the system. However, the actual implementation of the thread depends on the operating system where Java is running. As a result, threaded programs do take advantage of a thread-supported operating system.


When a thread is created, it can be given a priority. The higher the priority, the more it will affect the operating system. The Java runtime uses a scheduler that is responsible for running all existing programs within all of the executing Java applications. The scheduler actually uses a fixed-priority algorithm to ensure that the highest-priority threads in each program get cpu--to allow the highest-priority threads to execute before other threads.


For a situation where several threads of the same priority in a program are waiting to be executed, the scheduler scheduler selects them cyclically, and when the next selection is made, the thread that is not previously executed is selected, and all threads with the same priority are treated equally. A lower-priority thread can execute after a higher-priority thread has died or entered a non-executable state.


Continue discussion Wait (), notify (), Notifyall ():


When a thread executes a wait () call to a specific object, that thread is placed in the waiting pool associated with that object. Additionally, the thread that calls wait () automatically frees the object's lock flag.


You can call different wait (): Wait () or wait (long timeout)


When a notify () call is performed on a particular object, an arbitrary thread is removed from the object's wait pool and placed in the lock flag waiting pool, where the thread waits until the object's lock flag can be obtained. The Notifyall () method removes all the threads waiting for that object from the object waiting pool and puts it in the lock flag waiting pool. Only the lock flag waits for a thread in the pool to get the lock flag for the object, and the lock flag allows the thread to continue running from the last time it was interrupted by calling wait ().


In many systems that implement the Wait ()/notify () mechanism, the waking thread must be the thread that waits the longest. However, in Java technology, this is not guaranteed.


Note that notify () can be called regardless of whether the thread is waiting. If you call the Notify () method on an object, and there are no threads in the lock flag waiting pool for the object, then the Notify () call will have no effect.


In Java, multithreading is a magical theme. It is "magical" because the running results of multi-threaded procedures are unpredictable, but we can control the execution of multi-threaded threads in some ways. To be flexible with multi-threading, the reader needs a lot of practice.


Also, starting with JDK 1.2, Sun does not recommend the use of resume (), stop (), Suend ().

Http://www.jisu3d.com/2010/0525/16637.html

Java Technology topic Review Threads (1)

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.