Vamsi Krishna M
BAN USER@kulbhushan verma, you are right.
1. There is no guarantee that even thread will start first.
2. When does it stop?
We can add sleep(), but I dont think thats a feasible solution here.
wait also does the same thing as join.
Once the thread completes its execution, it just notifies everyone waiting on the Thread object.
Below program worked fine and the output is:
Thread-0 Thread3.run()
Thread-1 Thread3.run()
main Thread3.run()
package threads;
public class MyJoinClass {
public static void main(String[] args) {
Thread t1 = new Thread3();
Thread t2 = new Thread3();
t1.start();
myJoin(t1);
t2.start();
myJoin(t2);
System.out.println(Thread.currentThread().getName() + " Thread3.run()");
}
private static void myJoin(Thread t) {
synchronized (t) {
if(t.getState() != Thread.State.TERMINATED)
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Thread3 extends Thread
{
@Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " Thread3.run()");
}
}
array v is the values of rods with length as index i.e. v[2] is the value of rod of length 2.
b is the array of max benefit of rod of length as index. b[2] is the maximum benifit we can get from rod of length 2.
// int[] v = {1,5,8,9}; // Array of values for each size
// int[] b = new int[val.length];
b[0] will be 0 as there is no value for no rod. b[1] is v[1] as we can not have any more combinations.
public int getMaxBenifit(int n) {
int sum = 0;
int val = 0;
b[0] = 0;
b[1] = v[1];
for(int k = 2; k<n; k++)
{
for(int i = i; i <= k ; i++) {
val = v[i] + b[k-i];
if(val > sum)
sum = val;
}
b[k] = sum;
}
}
This is a twisted inorder traversal question:
public int inOrder(Node node, int sum)
{
if(node == null)
{
return 0;
}
sum += inOrder(node.right, sum);
int t = node.data;
node.data = sum;
sum += t;
sum += inOrder(node.left, sum);
return sum;
}
From main, just call inOrder(root,0);
- Vamsi Krishna M March 18, 2014
- Vamsi Krishna M March 19, 2014