Programming In Java | Week 6

Programming In Java | Week 6

Course Link: https://onlinecourses.nptel.ac.in/noc23_cs74/course

Programming Assignment

1. Complete the code segment to print the following using the concept of extending the Thread class in Java:
—————–OUTPUT——————-
Thread is Running.
————————————————-

Solution:

public class Question61 extends Thread{
  public void run(){
		System.out.print("Thread is Running.");
  }

2. In the following program, a thread class Question62 is created using the Runnable interface Complete the main() to create a thread object of the class Question62 and run the thread. It should print the output as given below.
—————–OUTPUT——————-
Welcome to Java Week 6 New Question.
Main Thread has ended.
————————————————-

Solution:

public static void main(String[] args)
    {
            Question62 ex = new Question62();
            Thread t1= new Thread(ex);
            t1.setName("Main Thread");
            t1.start();
            System.out.println("Welcome to Java Week 6 New Question.");
            t1.setName("Main Thread");
    }

3. A part of the Java program is given, which can be completed in many ways, for example using the concept of thread, etc.  Follow the given code and complete the program so that your program prints the message “NPTEL Java week-6 new Assignment Q3”. Your program should utilize the given interface/ class.

Solution:

class MyThread extends B {
	// run() is overriden and 'NPTEL Java' is printed.
	public void run() {
 		System.out.print("NPTEL Java week-6 new Assignment Q3");
	}
}

4. Execution of two or more threads occurs in a random order. The keyword ‘synchronized’ in Java is used to control the execution of thread in a strict sequence. In the following, the program is expected to print the output as given below. Do the necessary use of ‘synchronized’ keyword, so that, the program prints the Final sum as given below:  
—————–OUTPUT——————-
Final sum:6000
————————————————-

 public synchronized int sum() {
        return(a+b);
    }

    // Increments both a and b. (writer)
    public synchronized void inc() {
        a++;
        b++;
    }
}

5. Given a snippet of code, add necessary codes to print the following:
—————–OUTPUT——————-
Name of thread ‘t1’:Thread-0
Name of thread ‘t2’:Thread-1
New name of thread ‘t1’:Week 6 Assignment Q5
New name of thread ‘t2’:Week 6 Assignment Q5 New
————————————————-

Solution:

t1.start();
  t1.setName("Week 6 Assignment Q5");

  t2.start();
  t2.setName("Week 6 Assignment Q5 New");

* The material and content uploaded on this website are for general information and reference purposes only !

Please do it by your own first!

DMCA.com Protection Status

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments



0
Would love your thoughts, please comment.x
()
x