Threads in Java (iii)

Source: Internet
Author: User

1. Multi-threaded data security

Class MyThread implements Runnable{int i = 100;public void Run {while (true) {//thread.currentthread (); Gets the thread in which the current thread is running 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 ();//Generate two thread objects, But these two thread objects share the same thread body thread t1 = new Thread (); Thread t2 = new Thread (),//each thread must have a name, the thread name can be set by the SetName () method of the Thread object, or the GetName method can be used to get the name T1.setname of the thread ("Thread A"); T2.setname ("thread B"); T1.start (); T2.start ();}}

sometimes it goes wrong: {Thread A 100 thread B 100 ...}

Workaround, add a synchronous 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 line enters upgradeable obtains this lock, which thread has the right to execute this code, the other thread can only wait for <span style= "White-space:pre" ></span>//a thread executes a piece of code, Another thread will no longer execute this code//thread.currentthread (); Gets the thread in which the current thread is running System.out.println (Thread.CurrentThread (). GetName () + i); i--; Thread.yield (); if (I < 0) {break;}}}}


2. Methods for synchronizing threads


Threads in Java (iii)

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.