The Wayback Machine - https://web.archive.org/web/20240930230620/https://www.geeksforgeeks.org/output-of-java-program-set-16-threads/
Open In App

Output of Java program | Set 16 (Threads)

Last Updated : 19 May, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: multi-threading in java , Life cycle and states of a thread , Joining threads in java , start() method in java
1) What could be the output of the following program?




public class Test implements Runnable
{
    public void run()
    {
        System.out.printf("GFG ");
        System.out.printf("Geeks ");
    }
    public static void main(String[] args)
    {
        Test obj = new Test();
        Thread thread = new Thread(obj);
          
        thread.start();
        System.out.printf("Geeks ");
        try 
        {
            thread.join();
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
        System.out.println("for ");
    }
}


a) GFG Geeks Geeks for
b) Geeks GFG Geeks for
c) Either a or b
d) Both a and b together

Ans. (c)
Explanation: From the statement “thread.start()”, we have two threads Main thread and “thread” thread. So either “GFG” can be printed or “Geeks”, depend on which thread, thread scheduler schedule.
For (a), the parent thread after calling start() method is paused and the thread scheduler schedules the child thread which then completes its execution. Following this, the parent thread is scheduled. For (b), the parent thread calls start() method but continues its execution and prints on the console. When join() method is called, the parent thread has to wait for its child to complete its execution. Thread scheduler schedules child thread while the parent waits for the child to complete.


2) What is the output of the following program?




public class Test implements Runnable
{
    public void run()
    {
        System.out.printf("GFG ");
    }
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Test());
        thread1.start();
        thread1.start();
        System.out.println(thread1.getState());
    }
}


a) GFG GFG TERMINATED
b) GFG TERMINATED
c) Compilation Error
d) Runtime Error

Ans. (d)
Explanation: Invoking start() method on a thread moves the thread to a RUNNABLE state. But invoking start() method on a thread that has already started throws a IllegalThreadStateException because the thread is already in RUNNABLE state.

3) What is the output of the following program?




public class Test extends Thread implements Runnable
{
    public void run()
    {
        System.out.printf("GFG ");
    }
    public static void main(String[] args) throws InterruptedException
    {
        Test obj = new Test();
        obj.run();
        obj.start();
    }
}


a) Runtime error
b) Compilation error
c) GFG GFG
d) None of the above
Ans. (c)
Explanation: Test class extends Thread class that has start() method implemented. So invoking start() on an object that extends Thread class invokes run() method defined in the program.

4) What is the output of the following program?




class myThread implements Runnable
{
    public void run()
    {
        Test.obj.notify();
    }
}
  
public class Test implements Runnable
{
    public static Test obj;
    private int data;
    public Test()
    {
        data = 10;
    }
    public void run()
    {
        obj = new Test();
        obj.wait();
        obj.data += 20;
          
        System.out.println(obj.data);
    }
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Test());
        Thread thread2 = new Thread(new myThread());
          
        thread1.start();
        thread2.start();
      
        System.out.printf(" GFG - ");   
    }
}


a) 30 GFG –
b) GFG – 30
c) GFG –
d) Compilation error

Ans. (d)
Explanation: An object must first acquire a lock before calling wait() method. Also wait() method throws Checked exception(InterruptedException), we must include it in a try-catch block or throws it.

5)What is the output of the following program?




import java.util.concurrent.*;
  
public class Test implements Runnable
{
    public static CyclicBarrier barrier = new CyclicBarrier(3);
    public void run()
    {
        System.out.printf(" GFG ");
        try 
        {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Test());
        Thread thread2 = new Thread(new Test());
          
        thread1.start();
        thread2.start();
        System.out.printf(" GeeksforGeeks ");
        try 
        {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) 
        {
            e.printStackTrace();
        }
        System.out.printf(" End ");
          
    }
}


a) GeeksforGeeks GFG GFG End
b) GFG GeeksforGeeks GFG End
c) GFG GFG GeeksforGeeks End
d) All the above

Ans. (d)
Explanation: For (a), the parent thread keep executing until it reaches the barrier. The child thread are then scheduled. For (b), thread scheduler scheduler thread1. Once it reaches the barrier, the parent thread is scheduled. Once parent thread reached the barrier, thread2 is scheduled. For (c), Both the child thread are scheduled. Finally when each of the child threads reach the barrier, the parent thread is scheduled.



Previous Article
Next Article

Similar Reads

Difference Between Daemon Threads and User Threads In Java
In Java, there are two types of threads: Daemon ThreadUser Thread Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks. Differ
4 min read
Output of Python program | Set 16 (Threads)
1) What is the output of the following program? import threading barrier = threading.Barrier(4) class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print("ThreadID = " + str(self.thread_ID) + ", ThreadName
3 min read
Killing threads in Java
A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads. But these methods were deprecated by Java 2 because they could result in system failures. Mod
7 min read
Virtual Threads in Java
In Java, Virtual threads are now supported by the Java Platform. Virtual threads are lightweight threads that greatly minimize the effort required to create, operate, and manage high volumes systems that are concurrent. As a result, they are more efficient and scalable than standard platform threads. A thread is the smallest processing unit that ca
8 min read
Joining Threads in Java
java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If there are multiple threads calling the join() method
3 min read
Java Threads
Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time). For example, in MS Word. one thread automatically formats the document while another thread is taking user i
9 min read
Output of Java Program | Set 1
Difficulty Level: Rookie Predict the output of the following Java Programs.Program 1: Java Code // filename Main.java class Test { protected int x, y; } class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.x + " " + t.y); } } Output: 0 0 In Java, a protected member is accessible in all cl
3 min read
Output of Java Program | Set 2
Predict the output of the following Java programs. Question 1: Java Code package main; class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main { public static void DoPrint(Base o) { o.Print(); } public static void main(Str
3 min read
Output of Java Program | Set 3
Predict the output of the following Java Programs: Example1: Java Code // filename: Test.java class Test { // Declaring and initializing integer variable int x = 10; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Printing the value inside the object by // above cre
3 min read
Output of Java Program | Set 4
Predict the output of following Java Programs: Question 1 // file name: Main.java class Base { protected void foo() {} } class Derived extends Base { void foo() {} } public class Main { public static void main(String args[]) { Derived d = new Derived(); d.foo(); } } Output: Compiler Error foo() is protected in Base and default in Derived. Default a
2 min read
Output of Java Program | Set 11
Predict the output of following Java programs: Question 1 : public class Base { private int data; public Base() { data = 5; } public int getData() { return this.data; } } class Derived extends Base { private int data; public Derived() { data = 6; } private int getData() { return data; } public static void main(String[] args) { Derived myData = new
4 min read
Output of Java Program | Set 20 (Inheritance)
Prerequisite - Inheritance in Java Predict the output of following Java Programs. Program 1 : class A { public A(String s) { System.out.print("A"); } } public class B extends A { public B(String s) { System.out.print("B"); } public static void main(String[] args) { new B("C"); System.out.println(" "); } } Out
3 min read
Output of Java program | Set 22 (Overloading)
Prerequisite - Overloading in Java1) What is the output of the following program? Java Code public class Test { public int getData() //getdata() 1 { return 0; } public long getData() //getdata 2 { return 1; } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.getData()); } } a) 1 b) 0 c) Runtime error d) Compilat
3 min read
Output of Java program | Set 27
Ques1. What is the output of the following? import java.util.*; public class Test { public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } } Options : A. The program has a compile error because the size of the array wasn't specified when declaring the array. B. The program has a runtime err
3 min read
Output of Java program | Set 28
Question 1. What is the output of the following question? class Test { int a = 10; static int b = 20; public static void main(String[] args) { Test t1 = new Test(); t1.a = 100; t1.b = 200; Test t2 = new Test(); System.out.println("t1.a =" + t1.a + " t1.b =" + t1.b); System.out.println("t2.a =" + t2.a + " t2.b =
4 min read
Output of Java program | Set 26
Ques1: What is the output of this program? [GFGTABS] Java class A { public int i; private int j; } class B extends A { void display() { super.j = super.i + 1; System.out.println(super.i + " " + super.j); } } class inheritance { public static void main(String args[]) { B obj = new B(); obj.i = 1; obj.j = 2; obj.display(); } } [/GFGTABS]a)
4 min read
Output of C++ Program | Set 1
Predict the output of below C++ programs. Question 1 // Assume that integers take 4 bytes. #include<iostream> using namespace std; class Test { static int i; int j; }; int Test::i; int main() { cout << sizeof(Test); return 0; } Output: 4 (size of integer) static data members do not contribute in size of an object. So 'i' is not consider
1 min read
Output of C Program | Set 17
Predict the output of following C programs. Question 1 #include<stdio.h> #define R 10 #define C 20 int main() { int (*p)[R][C]; printf("%d", sizeof(*p)); getchar(); return 0; } Output: 10*20*sizeof(int) which is "800" for compilers with integer size as 4 bytes. The pointer p is de-referenced, hence it yields type of the object. In t
2 min read
Output of C++ Program | Set 3
Predict the output of below C++ programs.Question 1 C/C++ Code #include<iostream> using namespace std; class P { public: void print() { cout <<" Inside P::"; } }; class Q : public P { public: void print() { cout <<" Inside Q"; } }; class R: public Q { }; int main(void) { R r; r.print(); return 0; } Output: Insi
2 min read
Output of C Program | Set 18
Predict the output of following C programs.Question 1 C/C++ Code #include<stdio.h> int fun() { static int num = 40; return num--; } int main() { for(fun(); fun(); fun()) { printf("%d ", fun()); } getchar(); return 0; } Output: 38 35 32 29 26 23 20 17 14 11 8 5 2Since num is static in fun(), the old value of num is preserved for subs
2 min read
Output of C Program | Set 19
Predict the outputs of following program. Difficulty Level: Rookie Question 1 #include <stdio.h> int main() { int a = 10, b = 20, c = 30; if (c > b > a) { printf("TRUE"); } else { printf("FALSE"); } getchar(); return 0; } Output: FALSE Let us consider the condition inside the if statement. Since there are two greater
1 min read
Output of C Program | Set 20
Predict the outputs of following C programs. Question 1 int main() { int x = 10; static int y = x; if(x == y) printf("Equal"); else if(x > y) printf("Greater"); else printf("Less"); getchar(); return 0; } Output: Compiler Error In C, static variables can only be initialized using constant literals. See this GFact fo
2 min read
Output of C++ Program | Set 4
Difficulty Level: Rookie Predict the output of below C++ programs. Question 1 #include<iostream> using namespace std; int x = 10; void fun() { int x = 2; { int x = 1; cout << ::x << endl; } } int main() { fun(); return 0; } Output: 10 If Scope Resolution Operator is placed before a variable name then the global variable is referen
2 min read
Output of C++ Program | Set 5
Difficulty Level: RookiePredict the output of below C++ programs.Question 1 C/C++ Code #include<iostream> using namespace std; class Test { int value; public: Test(int v); }; Test::Test(int v) { value = v; } int main() { Test t[100]; return 0; } Output: Compiler error The class Test has one user defined constructor "Test(int v)" that expects
2 min read
Output of C++ Program | Set 6
Predict the output of below C++ programs. Question 1 #include<iostream> using namespace std; class Test { int value; public: Test (int v = 0) {value = v;} int getValue() { return value; } }; int main() { const Test t; cout << t.getValue(); return 0; } Output: Compiler Error. A const object cannot call a non-const function. The above cod
2 min read
Output of C Program | Set 21
Predict the output of following C programs. Question 1 C/C++ Code #include&lt;stdio.h&gt; #define fun (x) (x)*10 int main() { int t = fun(5); int i; for(i = 0; i &lt; t; i++) printf(&quot;GeeksforGeeks\n&quot;); return 0; } Output: Compiler Error There is an extra space in macro declaration which causes fun to be replaced by (x)
2 min read
Output of C++ Program | Set 7
Predict the output of following C++ programs. Question 1 class Test1 { int y; }; class Test2 { int x; Test1 t1; public: operator Test1() { return t1; } operator int() { return x; } }; void fun ( int x) { }; void fun ( Test1 t ) { }; int main() { Test2 t; fun(t); return 0; } Output: Compiler Error There are two conversion operators defined in the Te
2 min read
Output of C++ Program | Set 9
Predict the output of following C++ programs. Question 1 template <class S, class T> class Pair { private: S x; T y; /* ... */ }; template <class S> class Element { private: S x; /* ... */ }; int main () { Pair <Element<int>, Element<char>> p; return 0; } Output: Compiler Error: '>>' should be '> >' within a nested tem
2 min read
Output of C Program | Set 22
Predict the output of following C programs.Question 1: C/C++ Code #include<stdio.h> int main() { enum channel {star, sony, zee}; enum symbol {hash, star}; int i = 0; for(i = star; i <= zee; i++) { printf("%d ", i); } return 0; } Output: compiler error: redeclaration of enumerator 'star' In the above program, enumeration constant
2 min read
Output of C++ Program | Set 10
Predict the output of following C++ programs.Question 1 C/C++ Code #include<iostream> #include<string.h> using namespace std; class String { char *p; int len; public: String(const char *a); }; String::String(const char *a) { int length = strlen(a); p = new char[length +1]; strcpy(p, a); cout << "Constructor Called " <
2 min read