Home > Java > javaTutorial > body text

Full decryption of Java multi-threaded application methods

黄舟
Release: 2016-12-15 10:04:50
Original
1658 people have browsed it

Java multi-threading is something we use very often, and there are many application methods in the process of continuous learning. Let’s learn these key methods below. Hope this helps. First, let’s take a look at the specific method classification.

  Methods commonly used in Java multi-threaded programs include the following: run(), start(), wait(), sleep(), notify(), notifyAll(), yield(), join(), and There is an important keyword synchronized. These methods are explained below:

1. run() and start()

These two methods should be familiar. Put the code that needs parallel processing in the run() method, and the start() method starts the thread. The run() method will be called automatically, which is specified by Java's memory mechanism. And the run() method must have public access permissions and the return value type is void.

  2. Keyword Synchronized

 This keyword is used to protect shared data. Of course, the premise is to distinguish which data is shared data. Each object has a lock flag. When a thread accesses the object, the data modified by Synchronized will be "locked", preventing other threads from accessing it. After the current thread has accessed this part of the data, it releases the lock flag, and other threads can access it.

 1.public ThreadTest implements Runnable

 2.{

 3.public synchronized void run(){

 4.for(int i=0;i<10;i++)

 5.{

 6. System.out.println(" " + i);

 7.}

 8.}

 9.public static void main(String[] args)

 10.{

 11.Runnable r1 = new ThreadTest ();

 12.Runnable r2 = new ThreadTest();

 13.Thread t1 = new Thread(r1);

 14.Thread t2 = new Thread(r2);

 15.t1.start() ;

 16.t2.start();

 17.}

 18.}

 The i variable in the above program is not shared data, that is, the Synchronized keyword here does not work. Because the two threads t1 and t2 are threads of two objects (r1, r2). Different objects have different data, so the i variable of the two objects r1 and r2 does not share data.

  When the code is changed to the following: the Synchronized keyword will work

  19.Runnable r = new ThreadTest();

  20.Thread t1 = new Thread(r);

  21.Thread t2 = new Thread (r);

 22.t1.start();

 23.t2.start();

  The above is a detailed introduction to Java multi-threading. For more related articles, please pay attention to the PHP Chinese website (www.php. cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template