Thread Synchronization (2)

Source: Internet
Author: User

In thread synchronization when a method is marked as synchronize, other threads are not accessible at the same time, but other methods and properties can be accessed, and data can be changed.

Instance:

Package com.exmaple.Thread;

public class Test6 implements runnable{

/**
* When a method is marked as synchronize in thread synchronization, other threads cannot be accessed concurrently
* But you can access other methods and properties, and you can change the data.
* @param args
*/
static thread thread;
private static number num;
public static void Main (string[] args) {
TODO auto-generated Method Stub
Num=new number ();
Test6 t=new Test6 ();
Thread t1=new thread (t);
T1.start ();

try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Num.f2 ();
}
@Override
public void Run () {
TODO auto-generated Method Stub
NUM.F1 ();
}

}
Class Number {
int i=10;
Public synchronized void F1 () {
i=100;
try {
Thread. Sleep (5000);
} catch (Exception e) {
Todo:handle exception
}
System.out.println ("i=" +i);
}
public void F2 () {

try {
Thread. Sleep (2000);
} catch (Exception e) {
Todo:handle exception
}
i=200;
}
}

Description: In the main thread from the creation of a child thread, the child thread executes, i=100, enters sleep, and the method is locked. Meanwhile, the main thread executes the following code F2 (), I is changed i=200;, Child thread sleep wake, output

Thread Synchronization (2)

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.