SlideShare una empresa de Scribd logo
1 de 14
Threads
Duration : 30 mins
1. What will be the result of attempting to compile and run the following program?

public class MyThread implements Runnable
{
  String msg = "default";
  public MyThread(String s)
  {
    msg = s;
  }
  public void run( )
  {
    System.out.println(msg);
  }
  public static void main(String args[])
  {
    new Thread(new MyThread("String1")).run();
    new Thread(new MyThread("String2")).run();
    System.out.println("end");
  }
}

Select 1 correct option.
a The program will compile and print only 'end'.
b It will always print 'String1' 'String2' and 'end', in that order.
c It will always print 'String1' 'String2' in random order followed by 'end'.
d It will always print 'end' first.
e No order is guaranteed.
2. The following program will always terminate.

class Base extends Thread
{
               static int k = 10;
}
class Incrementor extends Base
{
               public void run()
               {
                                    for(; k>0; k++)
                                    {
                                                      System.out.println("IRunning...");
                                    }
              }
}
class Decrementor extends Base
{
              public void run()
              {
                                for(; k>0; k--)
                                {
                                                      System.out.println("DRunning...");
                                    }
                }
}
public class TestClass
{
                public static void main(String args[]) throws Exception
                {
                                  Incrementor i = new Incrementor();
                                  Decrementor d = new Decrementor();
                                  i.start();
                                  d.start();
                }
}

Select 1 correct option.
a True


b False
3. What will happen if you run the following program...

public class TestClass extends Thread
{
  public void run()
  {
    for(;;);
  }
  public static void main(String args[])
  {
    System.out.println("Starting main");
    new TestClass().start();
    System.out.println("Main returns");
  }
}

Select 3 correct options
a It will print "Starting Main"
b It will print "Main returns"
c It will not print "Main returns"
d The program will never exit.
e main() method will never return
4. What will be the result of attempting to compile and run the following program?

public class Test extends Thread
{
  String msg = "default" ;
  public Test(String s)
  {
    msg = s;
  }
  public void run()
  {
    System.out.println(msg);
  }
  public static void main(String args[])
  {
    new Test("String1").start();
    new Test("String2").start();
    System.out.println("end");
  }
}

Select 1 correct option.
a The program will fail to compile.
b It will always print 'String1' 'String2' and 'end', in that order.
c It will always print 'String1' 'String2' in random order followed by 'end'.
d It will always print 'end' first.
e No order is guaranteed.
5. Which of these statements are true?

Select 2 correct options
a Calling the method sleep( ) does not kill a thread.

b A thread dies when the start( ) method ends.

c A thread dies when the thread's constructor ends.

d A thread dies when the run( ) method ends.

e Calling the method kill( ) stops and kills a thread.
6. What will be the output when the following code is run?

class MyRunnable implements Runnable
{
            MyRunnable(String name)
            {
                         new Thread(this, name).start();
            }
            public void run()
            {
                         System.out.println(Thread.currentThread().getName());
            }
}
public class TestClass
{
            public static void main(String[] args)
            {
                         Thread.currentThread().setName("MainThread");
                         MyRunnable mr = new MyRunnable("MyRunnable");
                         mr.run();
            }
}

Select 1 correct option.
a MainThread
b MyRunnable
c "MainThread" will be printed twice.
d "MyRunnable" will be printed twice.
e It will print "MainThread" as well as "MyRunnable"
7. What do you need to do to define and start a thread?

Select 1 correct option.
a Extend from class Thread, override method run() and call method start();

b Extend from class Runnable, override method run() and call method
start();

c Extend from class Thread, override method start() and call method run();

d Implement interface Runnable and call start()

e Extend from class Thread, override method start() and call method start();
8. Consider the following code:

class MyClass implements Runnable
{
            int n = 0;
            public MyClass(int n){ this.n = n; }
            public static void main(String[] args)
            {
                       new MyClass(2).run();
                       new MyClass(1).run();
            }
            public void run()
            {
                       for(int i=0; i<n; i++)
                       {
                                   System.out.println("Hello World");
                       }
            }
}
What is true about above program?
Select 1 correct option.
a It'll print "Hello World" twice.
b It'll keep printing "Hello World".
c 2 new threads are created by the program.
d 1 new thread is created by the program.
e None of these.
9. Consider the following code:

class MyRunnable implements Runnable
{
            public static void main(String[] args)
            {
                      new Thread( new MyRunnable(2) ).start();
            }
            public void run(int n)
            {
                      for(int i=0; i<n; i++)
                      {
                                 System.out.println("Hello World");
                      }
            }
}
What will be the output when this program is compiled and run from the command line?
Select 1 correct option.
a It'll print "Hello World" once.
b It'll print "Hello World" twice.
c This program will not even compile.
d This will compile but will throw an exception at runtime.
e It will compile and run but it will not print anything.
10. Consider the following program...
public class TestClass implements Runnable
{
  int x = 5;
  public void run()
  {
    this.x = 10;
  }
  public static void main(String[] args)
  {
     TestClass tc = new TestClass();
     new Thread(tc).start(); // 1
     System.out.println(tc.x);
  }
}
What will it print when run?


Select 1 correct option.
a 5
b 10
c It will not compile.
d Exception at Runtime.
e The output cannot be determined.
11 Which of the following statements about this program are correct?

class CoolThread extends Thread
{
          String id = "";
          public CoolThread(String s){ this.id = s; }
          public void run()
          {
                     System.out.println(id+"End");
          }
          public static void main(String args [])
          {
                     Thread t1 = new CoolThread("AAA");
                     t1.setPriority(Thread.MIN_PRIORITY);
                     Thread t2 = new CoolThread("BBB");
                     t2.setPriority(Thread.MAX_PRIORITY);
                     t1.start();
          }
}
Select 1 correct option.
a "AAA End" will always be printed before "BBB End".
b "BBB End" will always be printed before "AAA End".
c The program will not compile.
d THe program will throw an exception at runtime.
e None of the above.
12. What will be the output when the following code is run?

class MyRunnable implements Runnable
{
             MyRunnable(String name)
             {
                          new Thread(this, name).start();
             }
             public void run()
             {
                          System.out.println(Thread.currentThread().getName());
             }
}
public class TestClass
{
             public static void main(String[] args)
             {
                          Thread.currentThread().setName("First");
                          MyRunnable mr = new MyRunnable("MyRunnable");
                          mr.run();
                          Thread.currentThread().setName("Second");
                          mr.run();
             }
}
Select 1 correct option.
a It will always print: First, MyRunnable, Second.
b It will always print: MyRunnable, First, Second.
c It will always print: First, Second, MyRunnable.
d It may print First, Second and MyRunnable in any order.
e Second will always be printed after First.
13. Consider the following class:

public class MySecureClass
{
           public synchronized void doALotOfStuff(){
                     try {
                     LINE1: Thread.sleep(10000);
                     }catch(Exception e){ }
           }
           public synchronized void doSmallStuff(){
                     System.out.println("done");
           }
}

Assume that there are two threads. Thread one is executing the doALotOfStuff() method and
has just

executed LINE 1. Now, Thread two decides to call doSmallStff() method on the same object.
What will happen?
Select 1 correct option.
a done will be printed immediately.
b done will not be printed untill about 10 seconds.
c done will never be printed.
d An IllegalMonitorStateException will be thrown.
e An IllegalThreadStateException will be thrown.

Más contenido relacionado

La actualidad más candente

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 

La actualidad más candente (20)

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Java programs
Java programsJava programs
Java programs
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
04 threads
04 threads04 threads
04 threads
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Import java
Import javaImport java
Import java
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Loop
LoopLoop
Loop
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Class method
Class methodClass method
Class method
 

Similar a Java Threads

Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
Dillon Lee
 

Similar a Java Threads (20)

Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
Java practical
Java practicalJava practical
Java practical
 
作業系統
作業系統作業系統
作業系統
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
14 thread
14 thread14 thread
14 thread
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
Java practical
Java practicalJava practical
Java practical
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
7
77
7
 
Java interface
Java interfaceJava interface
Java interface
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
STS4022 Exceptional_Handling
STS4022  Exceptional_HandlingSTS4022  Exceptional_Handling
STS4022 Exceptional_Handling
 

Último

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Java Threads

  • 2. 1. What will be the result of attempting to compile and run the following program? public class MyThread implements Runnable { String msg = "default"; public MyThread(String s) { msg = s; } public void run( ) { System.out.println(msg); } public static void main(String args[]) { new Thread(new MyThread("String1")).run(); new Thread(new MyThread("String2")).run(); System.out.println("end"); } } Select 1 correct option. a The program will compile and print only 'end'. b It will always print 'String1' 'String2' and 'end', in that order. c It will always print 'String1' 'String2' in random order followed by 'end'. d It will always print 'end' first. e No order is guaranteed.
  • 3. 2. The following program will always terminate. class Base extends Thread { static int k = 10; } class Incrementor extends Base { public void run() { for(; k>0; k++) { System.out.println("IRunning..."); } } } class Decrementor extends Base { public void run() { for(; k>0; k--) { System.out.println("DRunning..."); } } } public class TestClass { public static void main(String args[]) throws Exception { Incrementor i = new Incrementor(); Decrementor d = new Decrementor(); i.start(); d.start(); } } Select 1 correct option. a True b False
  • 4. 3. What will happen if you run the following program... public class TestClass extends Thread { public void run() { for(;;); } public static void main(String args[]) { System.out.println("Starting main"); new TestClass().start(); System.out.println("Main returns"); } } Select 3 correct options a It will print "Starting Main" b It will print "Main returns" c It will not print "Main returns" d The program will never exit. e main() method will never return
  • 5. 4. What will be the result of attempting to compile and run the following program? public class Test extends Thread { String msg = "default" ; public Test(String s) { msg = s; } public void run() { System.out.println(msg); } public static void main(String args[]) { new Test("String1").start(); new Test("String2").start(); System.out.println("end"); } } Select 1 correct option. a The program will fail to compile. b It will always print 'String1' 'String2' and 'end', in that order. c It will always print 'String1' 'String2' in random order followed by 'end'. d It will always print 'end' first. e No order is guaranteed.
  • 6. 5. Which of these statements are true? Select 2 correct options a Calling the method sleep( ) does not kill a thread. b A thread dies when the start( ) method ends. c A thread dies when the thread's constructor ends. d A thread dies when the run( ) method ends. e Calling the method kill( ) stops and kills a thread.
  • 7. 6. What will be the output when the following code is run? class MyRunnable implements Runnable { MyRunnable(String name) { new Thread(this, name).start(); } public void run() { System.out.println(Thread.currentThread().getName()); } } public class TestClass { public static void main(String[] args) { Thread.currentThread().setName("MainThread"); MyRunnable mr = new MyRunnable("MyRunnable"); mr.run(); } } Select 1 correct option. a MainThread b MyRunnable c "MainThread" will be printed twice. d "MyRunnable" will be printed twice. e It will print "MainThread" as well as "MyRunnable"
  • 8. 7. What do you need to do to define and start a thread? Select 1 correct option. a Extend from class Thread, override method run() and call method start(); b Extend from class Runnable, override method run() and call method start(); c Extend from class Thread, override method start() and call method run(); d Implement interface Runnable and call start() e Extend from class Thread, override method start() and call method start();
  • 9. 8. Consider the following code: class MyClass implements Runnable { int n = 0; public MyClass(int n){ this.n = n; } public static void main(String[] args) { new MyClass(2).run(); new MyClass(1).run(); } public void run() { for(int i=0; i<n; i++) { System.out.println("Hello World"); } } } What is true about above program? Select 1 correct option. a It'll print "Hello World" twice. b It'll keep printing "Hello World". c 2 new threads are created by the program. d 1 new thread is created by the program. e None of these.
  • 10. 9. Consider the following code: class MyRunnable implements Runnable { public static void main(String[] args) { new Thread( new MyRunnable(2) ).start(); } public void run(int n) { for(int i=0; i<n; i++) { System.out.println("Hello World"); } } } What will be the output when this program is compiled and run from the command line? Select 1 correct option. a It'll print "Hello World" once. b It'll print "Hello World" twice. c This program will not even compile. d This will compile but will throw an exception at runtime. e It will compile and run but it will not print anything.
  • 11. 10. Consider the following program... public class TestClass implements Runnable { int x = 5; public void run() { this.x = 10; } public static void main(String[] args) { TestClass tc = new TestClass(); new Thread(tc).start(); // 1 System.out.println(tc.x); } } What will it print when run? Select 1 correct option. a 5 b 10 c It will not compile. d Exception at Runtime. e The output cannot be determined.
  • 12. 11 Which of the following statements about this program are correct? class CoolThread extends Thread { String id = ""; public CoolThread(String s){ this.id = s; } public void run() { System.out.println(id+"End"); } public static void main(String args []) { Thread t1 = new CoolThread("AAA"); t1.setPriority(Thread.MIN_PRIORITY); Thread t2 = new CoolThread("BBB"); t2.setPriority(Thread.MAX_PRIORITY); t1.start(); } } Select 1 correct option. a "AAA End" will always be printed before "BBB End". b "BBB End" will always be printed before "AAA End". c The program will not compile. d THe program will throw an exception at runtime. e None of the above.
  • 13. 12. What will be the output when the following code is run? class MyRunnable implements Runnable { MyRunnable(String name) { new Thread(this, name).start(); } public void run() { System.out.println(Thread.currentThread().getName()); } } public class TestClass { public static void main(String[] args) { Thread.currentThread().setName("First"); MyRunnable mr = new MyRunnable("MyRunnable"); mr.run(); Thread.currentThread().setName("Second"); mr.run(); } } Select 1 correct option. a It will always print: First, MyRunnable, Second. b It will always print: MyRunnable, First, Second. c It will always print: First, Second, MyRunnable. d It may print First, Second and MyRunnable in any order. e Second will always be printed after First.
  • 14. 13. Consider the following class: public class MySecureClass { public synchronized void doALotOfStuff(){ try { LINE1: Thread.sleep(10000); }catch(Exception e){ } } public synchronized void doSmallStuff(){ System.out.println("done"); } } Assume that there are two threads. Thread one is executing the doALotOfStuff() method and has just executed LINE 1. Now, Thread two decides to call doSmallStff() method on the same object. What will happen? Select 1 correct option. a done will be printed immediately. b done will not be printed untill about 10 seconds. c done will never be printed. d An IllegalMonitorStateException will be thrown. e An IllegalThreadStateException will be thrown.