Thread synchronization | SoloLearn: Learn to code for FREE!

0

Thread synchronization

In this thread synchronization program is it necessary to create constructor of t class and pass ex as parameter to call the display()? Can we not simply make an object of example class in t class and call display method directly without creating a constructor and even in main method we can just create an object of t class and call start method directly which will implicitly call the run method in t class? https://code.sololearn.com/cGrlJJppXhvJ/?ref=app

4/21/2020 10:04:51 AM

Sagar Gupta

3 Answers

New Answer

+1

All of the threads share the same object e which is instance of class Example. In display() method the calling thread is identified by the call of Thread.currentThread() static method. You can define display() method as static. If you create an object inside class T then each object of T (thread) will have its own object of class Example and you don't need to call Thread.currentThread(), you can pass calling thread name as parameter of display.. I don't know the purpose of an example, may be that code shows an example of use the Thread.currentThread() static method?

+1

If all objects of class T have its own object of class Example the only difference will be the memory consumption. You will have 3 (in this example) the same objects instead of 1 if you create them inside class T. The constructor is defined to initialize member 'e'. You can define member 'e' as static, in this case you don't need to define the constructor, for example: //..... Definition of class Example //..... class T extends Thread { static Example e = new Example(); public void run() { e.display(); } } //....... public static void main(String args[]) { T t1 = new T(); T t2 = new T(); T t3 = new T(); t1.start(); t2.start(); t3.start(); } In this case you have only one instance of class Example which will be shared by all threads (instances of class T).

0

andriy kan is it necessary to create constructor t in class t? And what difference will it make if all objects of class t will have different objects of class example?