A detailed analysis of all the methods in Java multithreading technology

Source: Internet
Author: User

One, run () and start ()

Both methods should be familiar, putting code that requires parallel processing in the run () method, and the start () method starts the thread to automatically invoke the run () method, as defined by the Java memory mechanism. and the run () method must be public access and the return value type is void.

Second, the key word synchronized

This keyword is used to protect shared data, but the prerequisite is to distinguish between which data is shared data. Each object has a lock flag, and when a thread accesses the object, the data decorated by the synchronized is "locked" to prevent other threads from accessing it. When the current thread has finished accessing this part of the data, the lock flag is released and other threads are accessible.

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

The I variables in this program are not shared data, which means that the synchronized keyword here doesn't work. Because t1,t2 two threads are threads of two objects (R1,R2). Different objects have different data, so the I variable of the R1 and R2 two objects is not shared data.

When the code is changed as follows: The Synchronized keyword works

Runnable r = new ThreadTest ();

thread T1 = new Thread (r);

Thread t2 = new Thread (r);

T1.start ();

T2.start ();

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.