简体   繁体   中英

Multiple threads accessing same class

I have 4 threads running at same time trying to access following four different methods of same class. I want to know in which order will the threads execute.

public void method1();
public static void method2(); 
public synchronized void method3();
public static synchronized method4();

method1 is called by T1 method2 is called by T2 method3 is called by T3 method4 is called by T4

All the above methods are in the same class. I am totally confused on which order threads will run. Request your help.

The threads will run semi-parallelly. If you do not synchronize them, they can run in arbitrary order.

The synchronization methods you gave in your example are not effecting each other. The first 2 has no synchronization at all, the third syncs on the Object instance, the fourth syncs on the Class . So, the four threads can run in any particular order.

Synchronization required. Follow this Link for Synchronization : http://www.tutorialspoint.com/java/java_thread_synchronization.htm

It's totally impossible to predict thread orders. It's the whole responsibility of the JVM, not the programmer, and there isn't a basic law.

Synchronization doesn't help at all for that. It just allows to ensure atomicity and memory barrier.

The most known "issue" due to this fact could be: Race Condition where it is touchy to control programmers' decision about threads.

There is no way to know this. All threads run concurrently based on the amount of CPUs/cores in the system, and the prioritization of the system, and the load on the system as a whole. As such it's a matter of chance mostly which thread gets a chance to execute some code.

The seemingly arbitrary nature of thread schedulers is also what makes debugging race conditions, livelocks and deadlocks so much 'fun' to developers. There is no way to predict reliably how the OS executes your code when you're not using (enough) synchronization mechanisms.

The order that the threads will execute will depend on a variety of factors, so the real question is what order do you want them to execute in, and under what conditions will that order change?

Once you've worked that out, you can force a thread to wait on , or block, another thread, until it has completed. That is the most common approach to threaded programming in most languages/environments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM