Tuesday, December 4, 2018

Multithreading in Java



What is a Java Thread?

A thread is actually a lightweight process. Unlike many other computer languages, Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called thread and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
Next concept in this Java Thread blog is integral to the concept Threads and Multithreading.

The Java Thread Model

The Java run-time system depends on threads for many things. Threads reduce inefficiency by preventing the waste of CPU cycles.
Threads exist in several states. Following are those states:  
  • New – When we create an instance of Thread class, a thread is in a new state.
  • Runnable – The Java thread is in running state.
  • Running – A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off.
  • Waiting – A java thread can be blocked when waiting for a resource.
  • Dead – A thread can be terminated, which halts its execution immediately at any given time. Once a thread is terminated, it cannot be resumed. 



Multithreading in Java : Thread Class and Runnable Interface

Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. To create a new thread, your program will either extend Thread or implement the Runnableinterface.
The Thread class defines several methods that help manage threads.The table below displays the same:
Method Meaning
getName()Obtain thread’s name
getPriority()Obtain thread’s priority
isAlive()Determine if a thread is still running
join()Wait for a thread to terminate
run()Entry point for the thread
sleep()Suspend a thread for a period of time
start()Start a thread by calling its run method

Why is Main Thread so important?

  • Because this thread effects the other ‘child’ threads
  • Because it performs various shutdown actions
  • It is created automatically when your program is started.

How to Create a Java Thread? 

Java lets you create thread in following two ways:- 
  • By implementing the Runnable interface.
  • By extending the Thread

Runnable Interface

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable interface, a class need only implement a single method called run( ), which is declared like this:
1
public void run( )
Inside run( ), we will define the code that constitutes the new thread
Example:
1
2
3
4
5
public class MyClass implements Runnable {
public void run(){
System.out.println("MyClass running");
   }
}
To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor(constructor in Java is a block of code similar to a method that’s called when an instance of an object is created). Here is how that is done:
1
2
Thread t1 = new Thread(new MyClass ());
t1.start();
When the thread is started it will call the run() method of the MyClass instance instead of executing its own run() method. The above example would print out the text “MyClass running“.

Extending Java Thread

The second way to create a thread is to create a new class that extends Thread, then override the run() method and then to create an instance of that class. The run() method is what is executed by the thread after you call start(). Here is an example of creating a Java Thread subclass:
1
2
3
4
5
public class MyClass extends Thread {
     public void run(){
     System.out.println("MyClass running");
   }
}
To create and start the above thread you can do like this:
1
2
MyClass t1 = new MyClass ();
T1.start();
When the run() method executes it will print out the text “MyClass running“.
So far, we have been using only two threads: the main thread and one child thread. However, our program can affect as many threads as it needs. Let’s see how we can create multiple threads.

Creating Multiple Threads

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MyThread implements Runnable {
String name;
Thread t;
    MyThread String thread){
    name = threadname;
    t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
 
 
public void run() {
 try {
     for(int i = 5; i > 0; i--) {
     System.out.println(name + ": " + i);
      Thread.sleep(1000);
}
}catch (InterruptedException e) {
     System.out.println(name + "Interrupted");
}
     System.out.println(name + " exiting.");
}
}
 
class MultiThread {
public static void main(String args[]) {
     new MyThread("One");
     new MyThread("Two");
     new NewThread("Three");
try {
     Thread.sleep(10000);
} catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
}
      System.out.println("Main thread exiting.");
      }
}

OUTPUT:

New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting.

Sunday, December 2, 2018

C++ Inheritance



 Inheritance is one of the key features of Object-oriented programming in C++. It allows user to create a new class (derived class) from an existing class(base class).
The derived class inherits all the features from the base class and can have additional features of its own.

Why inheritance should be used?

Suppose, in your game, you want three characters - a maths teacher, a footballerand a businessman.
Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A maths teacher can teach maths, a footballer can play football and a businessman can run a business.
You can individually create three classes who can walk, talk and perform their special skill as shown in the figure below.
In each of the classes, you would be copying the same code for walk and talk for each character.
If you want to add a new feature - eat, you need to implement the same code for each character. This can easily become error prone (when copying) and duplicate codes.
It'd be a lot easier if we had a Personclass with basic features like talk, walk, eat, sleep, and add special skills to those features as per our characters. This is done using inheritance.
Using inheritance, now you don't implement the same code for walk and talk for each class. You just need to inherit them.
So, for Maths teacher (derived class), you inherit all features of a Person (base class) and add a new feature TeachMaths. Likewise, for a footballer, you inherit all the features of a Person and add a new feature PlayFootball and so on.
This makes your code cleaner, understandable and extendable.
It is important to remember: When working with inheritance, each derived class should satisfy the condition whether it "is a" base class or not. In the example above, Maths teacher is a Person, Footballer is a Person. You cannot have: Businessman is a Business.

Implementation of Inheritance in C++ Programming

class Person 
{
  ... .. ...
};

class MathsTeacher : public Person 
{
  ... .. ...
};

class Footballer : public Person
{
  .... .. ...
};
In the above example, class Person is a base class and classes MathsTeacher and Footballer are the derived from Person.


The derived class appears with the declaration of a class followed by a colon, the keyword public and the name of base class from which it is derived.


Since, MathsTeacher and Footballer are derived from Person, all data member and member function of Person can be accessible from them.


Example: Inheritance in C++ Programming


Create game characters using the concept of inheritance.

#include 
using namespace std;

class Person
{
     public:
        string profession;
        int age;

        Person(): profession("unemployed"), age(16) { }
        void display()
        {
             cout << "My profession is: " << profession << endl;
             cout << "My age is: " << age << endl;
             walk();
             talk();
        }
        void walk() { cout << "I can walk." << endl; }
        void talk() { cout << "I can talk." << endl; }
};

// MathsTeacher class is derived from base class Person.
class MathsTeacher : public Person
{
    public:
       void teachMaths() { cout << "I can teach Maths." << endl; }
};

// Footballer class is derived from base class Person.
class Footballer : public Person
{
    public:
       void playFootball() { cout << "I can play Football." << endl; }
};

int main()
{
     MathsTeacher teacher;
     teacher.profession = "Teacher";
     teacher.age = 23;
     teacher.display();
     teacher.teachMaths();

     Footballer footballer;
     footballer.profession = "Footballer";
     footballer.age = 19;
     footballer.display();
     footballer.playFootball();

     return 0;
}







Output:


My profession is: Teacher
My age is: 23
I can walk.
I can talk.
I can teach Maths.
My profession is: Footballer
My age is: 19
I can walk.
I can talk.
I can play Football.

In this program, Person is a base class, while MathsTeacher and Footballer are derived from Person.


Person class has two data members - profession and age. It also has two member functions - walk() and talk().


Both MathsTeacher and Footballer can access all data members and member functions of Person.


However, MathsTeacher and Footballer have their own member functions as well: teachMaths() and playFootball() respectively. These functions are only accessed by their own class.


In the main() function, a new MathsTeacherobject teacher is created.


Since, it has access to Person's data members, profession and age of teacheris set. This data is displayed using the display() function defined in the Personclass. Also, the teachMaths() function is called, defined in the MathsTeacher class.


Likewise, a new Footballer object footballeris also created. It has access to Person's data members as well, which is displayed by invoking the display() function. The playFootball() function only accessible by the footballer is called then after.



Access specifiers in Inheritance


When creating a derived class from a base class, you can use different access specifiers to inherit the data members of the base class.


These can be public, protected or private.


In the above example, the base class Person has been inherited public-ly by MathsTeacher and Footballer.

IND vs AUS: Smith & Labuschagne Holds Fort As Fourth Test Ends Up In A Stalemate

  Beginning on 158 after Tea for the loss of two wickets for visiting Australian side with two stalwarts Steve Smith and   Marnus Labuschagn...