Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Sunday, December 8, 2019

What will be the output of the below java code using volatile keyword?

Problem statement: Given code is
  1. public class Test extends Thread {
  2. private volatile int i = 0;
  3. public int getData() {
  4. return i + 1;
  5. }
  6. public void run() {}
  7. public static void main(String[] args) {
  8. Test t1 = new Test();
  9. t1.start();
  10. System.out.println("First thread: " + t1.getData());
  11. Test t2 = new Test();
  12. t2.start();
  13. System.out.println("Second thread: " + t2.getData());
  14. Test t3 = new Test();
  15. t3.start();
  16. System.out.println("Third thread: " + t3.getData());
  17. }
  18. }
Output:
First thread: 1
Second thread: 1
Third thread: 1

Saturday, May 11, 2019

what will be the output of thread problem?

Problem statement:
what will be the output of the following code?
  1. public class Person extends Thread {
  2.     private int count;
  3.     private Person(int count) {
  4.         this.count = count;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         for (int i = 1; i < 4; i++) {
  9.             count = count + 1;
  10.         }
  11.     }
  12.     public static void main(String[] args) {
  13.         Person t = new Person(10);
  14.         t.start();
  15.         System.out.println(t.count);
  16.     }
  17. }
Output: 10
output will vary, will explain the reason soon

what will be the output of thread code?

Problem statement:
what will be the output of the following code?
  1. public class ExecutionFourteen extends Thread {
  2.     private int count;
  3.     private ExecutionFourteen(int count) {
  4.         this.count = count;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         for (int i = 1; i < 4; i++) {
  9.             count = count + 1;
  10.             System.out.println("count inside run() method: " + count + ", thread name: " + Thread.currentThread().getName());
  11.         }
  12.     }
  13.     public static void main(String[] args) {
  14.         ExecutionFourteen t = new ExecutionFourteen(10);
  15.         t.start();
  16.         System.out.println("count inside main() method: " + t.count);
  17.     }
  18. }
Output:
count inside main() method: 10
count inside run() method: 11, thread name: Thread-0
count inside run() method: 12, thread name: Thread-0
count inside run() method: 13, thread name: Thread-0

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...