Multithreading in java
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" );
}
}
Interface Implementation
interface MyInterface
{
public void method1();
public void method2();
}
class XYZ implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new XYZ();
obj. method1();
}
}
Using classes to form
hybrid
public class A
{
public void methodA()
{
System.out.println("Class A methodA");
}
}
public class B extends A
{
public void methodA()
{
System.out.println("Child class B is overriding inherited method A");
}
public void methodB()
{
System.out.println("Class B methodB");
}
}
public class C extends A
{
public void methodA()
{
System.out.println("Child class C is overriding the methodA");
}
public void methodC()
{
System.out.println("Class C methodC");
}
}
public class D extends B, C
{
public void methodD()
{
System.out.println("Class D methodD");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodD();
obj1.methodA();
}
}
No comments:
Post a Comment