2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Will a static method execute parallel when two thread accessing

Will a static method execute parallel when two thread accessing. My doubt is if i have a static method and two different thread accessing the static method. If a static method is static always and is execute a task which is not yet complete, will the static method will start executing the other task where the previous task is not yet completed the execution.

userimage

I am not sure what you expecting but i did one test, hope this will help u to understand. If two thread calling a static method will execute parallel,


package test.statics;

/**
 * 
 * @author Debs
 *
 */
public class StaticTest {

	public static void testTask(String taskName) {
		for (int i = 0; i < 25; i++) {
			System.out.println(taskName + i);
		}
	}

	public static void main(String[] args) {
		new Thread(new Test1()).start();
		new Thread(new Test2()).start();
	}
}

class Test1 implements Runnable {

	@Override
	public void run() {
		StaticTest.testTask("Task 1 : ");
	}
}

class Test2 implements Runnable {

	@Override
	public void run() {
		StaticTest.testTask("Task 2 : ");
	}
}

Task 1 : 0
Task 1 : 1
Task 1 : 2
Task 1 : 3
Task 1 : 4
Task 1 : 5
Task 1 : 6
Task 1 : 7
Task 1 : 8
Task 2 : 0
Task 1 : 9
Task 2 : 1
Task 1 : 10
Task 2 : 2
Task 2 : 3
Task 1 : 11
Task 2 : 4
Task 1 : 12
Task 2 : 5
Task 1 : 13
Task 2 : 6
Task 2 : 7
Task 2 : 8
Task 2 : 9
Task 2 : 10
Task 2 : 11
Task 2 : 12
Task 1 : 14
Task 1 : 15
Task 1 : 16
Task 1 : 17
Task 1 : 18
Task 1 : 19
Task 1 : 20
Task 1 : 21
Task 1 : 22
Task 1 : 23
Task 1 : 24
Task 2 : 13
Task 2 : 14
Task 2 : 15
Task 2 : 16
Task 2 : 17
Task 2 : 18
Task 2 : 19
Task 2 : 20
Task 2 : 21
Task 2 : 22
Task 2 : 23
Task 2 : 24
Answer is