Can Java thread object invoke start method twice
package
com.java2novice.exmpcode;
public class
MyExmpCode extends Thread
{
public void run()
{
System.out.println("Run");
}
public static void main(String a[])
{
Thread t1 = new Thread(new
MyExmpCode());
t1.start();
t1.start();
}
}
Find out duplicate number between 1 to N numbers.
package com.java2novice.algos;
import java.util.ArrayList;
import java.util.List;
public class DuplicateNumber
{
public int findDuplicateNumber(List
numbers)
{
int highestNumber =
numbers.size() - 1;
int total =
getSum(numbers);
int duplicate = total -
(highestNumber*(highestNumber+1)/2);
return duplicate;
}
public int getSum(List
numbers)
{
int sum = 0;
for(int num:numbers)
{
sum
+= num;
}
return sum;
}
public static void main(String a[])
{
List
numbers = new ArrayList();
for(int i=1;i<30 i="" span="">30>
{
numbers.add(i);
}
numbers.add(22);
DuplicateNumber
dn = new DuplicateNumber();
System.out.println("Duplicate
Number: "+dn.findDuplicateNumber(numbers));
}
}
Find out middle index where sum of both ends are equal
package com.java2novice.algos;
public class FindMiddleIndex
{
public static int findMiddleIndex(int[]
numbers) throws Exception
{
int endIndex = numbers.length - 1;
int startIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true)
{
if (sumLeft >
sumRight)
{
sumRight
+= numbers[endIndex--];
}
else
{
sumLeft
+= numbers[startIndex++];
}
if (startIndex >
endIndex)
{
if (sumLeft == sumRight)
{
break;
}
else
{
throw new Exception("Please pass proper array to
match the requirement");
}
}
}
return endIndex;
}
public static void main(String a[])
{
int[]
num = { 2, 4, 4, 5, 4, 1 };
try
{
System.out.println("Starting
from index 0, adding numbers till index "+ findMiddleIndex(num) + "
and");
System.out.println("adding
rest of the numbers can be equal");
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
Write a singleton class
package com.java2novice.algos;
public class MySingleton
{
private static MySingleton myObj;
static
{
myObj
= new
MySingleton();
}
private MySingleton()
{
}
public static MySingleton
getInstance()
{
return myObj;
}
public void testMe()
{
System.out.println("Hey....
it is working!!!");
}
public static void main(String a[])
{
MySingleton
ms = getInstance();
ms.testMe();
}
}
Write a program to create deadlock between two threads
package com.java2novice.algos;
public class MyDeadlock
{
String str1 = "Java";
String
str2 = "Unix";
Thread trd1 = new Thread("My Thread
1")
{
public void run()
{
while(true)
{
synchronized(str1)
{
synchronized(str2)
{
System.out.println(str1 + str2);
}
}
}
}
};
Thread
trd2 = new Thread("My Thread 2")
{
public void run()
{
while(true)
{
synchronized(str2)
{
synchronized(str1)
{
System.out.println(str2
+ str1);
}
}
}
}
};
public static void main(String a[])
{
MyDeadlock
mdl = new MyDeadlock();
mdl.trd1.start();
mdl.trd2.start();
}
}
No comments:
Post a Comment