Java Thread Control security

Source: Internet
Author: User

Synchronized ()
Thread-safety issues sometimes occur when threads are running
For example: Ticket purchase process, there may be different window to buy the same number of tickets

Run the following code:

public class Runable implements Runnable {///Here the variable is defined as a variable of an object, when the run () function calls a different thread calls int i=1; @Overridepublic void Run () {while (true) {//output current thread name and number of votes System.out.println (Thread.CurrentThread (). GetName () +i); i++;//current thread discards CPU, re-competes resource Thread.yield (); if (i >100) Break;}}}

  

public class Main {public static void main (string[] args) throws Interruptedexception {//Implement Interface runable ra=new runable ();//Generate Thread object, and the interface object as the parameter thread t1=new thread (RA); Thread t2=new thread (RA);//Set name T1.setname ("Thread One") for two threads, T2.setname ("Thread Two");//Start thread T1.start (); T2.start ();}}

The following conditions can occur:

Processing method: Join the thread lock

public class Runable implements Runnable {///Here the variable is defined as a variable of an object, when the run () function calls a different thread calls int i=1; @Overridepublic void Run () {// Join the process lock, the lock is this object, before this object releases the CPU, all the code containing the process lock can not run synchronized (this) {while (true) {// Outputs the current thread name and number of votes System.out.println (Thread.CurrentThread (). GetName () +i), i++;//the current thread abandons the CPU, re-competes the resource Thread.yield (), if (i >100) Break;}}}

  

Java Thread Control security

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.