Java threads (3)

Source: Internet
Author: User

Java threads (3)

1. multi-threaded Data Security

Class MyThread implements Runnable {int I = 100; public void run {while (true) {// Thread. currentThread (); obtain the thread in which the current thread runs the System. out. println (Thread. currentThread (). getName () + I); I --; Thread. yield (); if (I <0) {break ;}}}}


Class Test {public static void main (String args []) {MyThread myThread = new MyThread (); // generates two Thread objects, however, these two Thread objects share the same Thread body Thread t1 = new Thread (); Thread t2 = new Thread (); // each Thread must be named, you can use the setName () method of the Thread object to set the Thread name, or use the getName method to obtain the Thread name t1.setName ("Thread a"); t2.setName ("Thread B "); t1.start (); t2.start ();}}

Sometimes an error occurs: {thread a 100 thread B 100 ...}

Solution: add the synchronization code block to the MyThread class.

Class MyThread implements Runnable {int I = 100; public void run {while (true) {synchronized (this) {// synchronized is a lock, which thread obtains the lock first, which Thread has the right to execute this code, and the other Thread can only wait // when one Thread is executing a code segment, the other Thread will no longer execute this code segment // Thread. currentThread (); obtain the thread in which the current thread runs the System. out. println (Thread. currentThread (). getName () + I); I --; Thread. yield (); if (I <0) {break ;}}}}}


2. synchronous thread method


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.