what is wrong with this java thread program - java

I am trying to figure out what is wrong with this thread program in java. Can anyone shed some light? Here is the code:
public class Z {
private Account account = new Account();
private Thread[] thread = new Thread[100];
public static void main(String[] args) {
Z test = new Z();
System.out.println("What is balance ? " + test.account.getBalance());
}
public Z() {
ThreadGroup g = new ThreadGroup("group");
boolean done = false;
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
thread[i] = new Thread(g, new AddAPennyThread(), "t" + i);
thread[i].start();
System.out.println("depositor: " + thread[i].getName());
}
// Check if all the threads are finished
while (!done)
if (g.activeCount() == 0)
done = true;
}
// A thread for adding a penny to the account
class AddAPennyThread extends Thread {
public void run() {
account.deposit(1);
}
}
// An inner class for account
class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
int newBalance = balance + amount;
balance = newBalance;
}
}
}
It compiles and runs fine. It was a test question I missed and wnated to know what is actually wrong with it. Thanks!

There is not a single bit dedicated to synchronization of 100 threads all working on exactly one (1!!!) piece of data.
Anything can happen. "Anything" includes that the code as it is works most of the time due some "coincidences":
The task at hand is quite small. (only an add)
The tasks are created and immediately started.
There is a small delay between two "create+start" pair: the System.out.println.
This adds up to: This might work in most test-runs. But it is an incorrect and non-deterministic program.

[Tread1] int newBalance = balance + amount;
[Tread2] int newBalance = balance + amount;
[Tread1] balance = newBalance;
[Tread2] balance = newBalance;
public synchronized void deposit(int amount)

balance should be a private volatile int (so that Java knows to never cache it - its value is liable to change between different thread accesses without the next thread knowing) and make Account#deposit(int amount) a public synchronized void (so that Java makes the method body a critical region and prevents simultaneous access of any of the objects it touches, ensuring the integrity of the value of balance).
Additionally, instantiating 100 threads yourself with new introduces a lot of overhead - though I appreciate this is just a toy example, a more efficient way to do this would be to use a Java thread pool.

Related

What is the difference between code that causes a deadlock vs one that prevents it? Need explanation for code example

I'm given code of a Banking example and I'm trying to figure out if this does produce a deadlock or not. If so, what part of the code achieves it? I would also like to know how I would alter the code to prevent deadlocks. I know it has something to do with the ordering of the methods but this code specifically confuses me. I'm new to networked programming so I'm still a little confused on this topic.
I have written this in Java.
public class Bank
{
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
}
public synchronized void transfer(int from, int to, double amount) throws InterruptedException
{
bankLock.lock();
try
{
while (accounts[from] < amount)
sufficientFunds.await();
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
sufficientFunds.signalAll();
}
finally
{
bankLock.unlock();
}
}
public synchronized double getTotalBalance()
{
bankLock.lock();
try
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
finally
{
bankLock.unlock();
}
}
public int size()
{
return accounts.length;
}
public class DeadlockApp
{
public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS,INITIAL_BALANCE);
for (int i = 0; i< NACCOUNTS; i++)
{
int fromAccount = i;
Runnable r = () ->
{
try
{
while (true)
{
int toAccount = (int) (bank.size() * Math.random());
double amount = MAX_AMOUNT * Math.random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int)(DELAY * Math.random()));
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
}
}
When I ran the code it was very slow and only produced two results so I couldn't tell if it was the deadlock that was going continuously or my IDE was just lagging.
The basic requirement for deadlocking is that two or more threads attempt to acquire a series of locks, but acquire them in varying order.
You have two locks in play, but your threads are all executing the same code, which has a fixed order of lock acquisition, and both locks can be recursively acquired, so there's no deadlock.
More specifically, only one thread at a time is executing in transfer by virtue of it being synchronized.
The locks are acquired in this order:
The Bank monitor (by 'synchronized' on transfer)
banklock (in transfer)
The Bank monitor again ('synchronized' on getTotalBalance) - but we hold it already so it will not block
banklock (in getTotalBalance) but we hold it already so it won't block
No deadlock, so there's some other cause for 'slowness'. My guess would be on how long the random actions take to build up sufficient funds.

which thread finished first in concurrent threads?

I am new in concurrent threads in java. I am trying to code a simple horse race simulation.
I want to know which thread finished first.
This code below throws an error: incompatible types: Thread cannot be converted to Gate
winner = (Gate)Thread.currentThread();
Gate.java
public class Gate implements Runnable{
public String horseName;
public final int GATE_DISTANCE = 20;
public final int FINISH_LINE_DISTANCE = 100;
public CyclicBarrier barrier;
public Gate(CyclicBarrier barrier,String horseName){
this.horseName = horseName;
this.barrier = barrier;
}
public void run(){
//Walk all horses to respective racing gates before starting race
for(int distanceCovered = 0; distanceCovered < GATE_DISTANCE;){
distanceCovered += gallop();
int distanceLeft = GATE_DISTANCE - distanceCovered;
if(distanceLeft < 0){
distanceLeft = 0;
}
System.out.println(horseName + "\t\tgate distance left " + distanceLeft);
if(distanceLeft == 0){
break;
}
}
//Wait for all horses to be at racing gates
try{
barrier.await();
}
catch(InterruptedException ie){
System.out.println("INTERRUPTED");
}
catch(BrokenBarrierException bbe){
System.out.println("BROKEN");
}
//ACTUAL HORSE RACE
for(int distanceCovered = 0; distanceCovered < FINISH_LINE_DISTANCE;){
distanceCovered += gallop();
int distanceLeft = FINISH_LINE_DISTANCE - distanceCovered;
if(distanceLeft < 0){
distanceLeft = 0;
}
System.out.println(horseName + "\t\tgate distance left " + distanceLeft);
if(distanceLeft == 0){
break;
}
}
Main.done();
}
public int gallop(){
final int MIN_GALLOP = 1,
MAX_GALLOP = 10;
Random random = new Random();
int gallopRange = MAX_GALLOP - MIN_GALLOP + 1;
int totalGallop = random.nextInt(gallopRange) + MIN_GALLOP;
return totalGallop;
}
}
GateMain.java
public class GateMain{
private static Gate winner = null;
public static void main(String[] args) {
int horseCount = 5;
List<String> horseNames = new ArrayList<String>();
List<Thread> RG = new ArrayList<Thread>();
horseNames.add("Red Bullet");
horseNames.add("Green Furious");
horseNames.add("Pink Mirage");
horseNames.add("Blue Dash");
horseNames.add("Yellow Burst");
Scanner scan = new Scanner(System.in);
final CyclicBarrier cb = new CyclicBarrier(horseCount,new Runnable(){
public void run(){
System.out.print("\nALL HORSES ARE IN THEIR RESPECTIVE RACING GATES");
System.out.println("\nRACE BEGIN!!!\n");
}
});
for(int horseCtr = 0; horseCtr < horseCount; horseCtr++){
Gate rg = new Gate(cb,horseNames.get(horseCtr));
Thread thread = new Thread(rg);
thread.start();
RG.add(thread);
}
for(Thread thread: RG){
try{
thread.join();
}
catch(InterruptedException ie){
System.out.println("Thread Interrupted");
}
}
System.out.println(winner.horseName + "\t\t\twins!");
}
synchronized static void done(){
if(winner == null){
winner = (Gate)Thread.currentThread();
}
}
}
I would use a global AtomicInteger.
public static AtomicInteger finishLine = new AtomicInteger(0);
Each horse (thread) should have its own place variable,
int place;
and when a horse finishes the race, it sets its own place:
place = finishLine.incrementAndGet();
The first horse to reach the finish line will get place=1, the second horse, place=2, and so on. Then the main() routine must then examine each horse to find out which one has place=1. That'll be the winner.
Here's a different idea, inspired by the finish-line of a cross-country foot race: Instead of an AtomicInteger, use a thread-safe queue.
public static ArrayBlockingQueue<Horse> chute =
new ArrayBlockingQueue<>(NUMBER_OF_HORSES);
When each horse reaches the finish line, it enters the chute.
chute.add(this);
This way, there is no need to explicitly wait for the race to end, and there is no need to explicitly sort the finishers:
Horse win = chute.take(); //waits for the first horse to finish
Horse place = chute.take(); //waits for the second horse
Horse show = chute.take(); //...
However, just synchronizing here will not work, according to the rules of Java. You have to synchronize the update that you want the thread to read, as well. Depending on what variable is, that may or may not be a problem.
You may need to think out your threading model a bit more, and describe here what you want to do. If you were unaware of mutual exclusion, you may not be ready to design threaded code.
if you're trying to access an instance field from a static member, I have to wonder how you got the code to compile.
Thread.currentThread() returns the actual Thread object you (or some other library code) created. That can be a Gate thread, but it all depends on the Thread object it is running in. Safest is to use instanceof to check first.
According to docs Thread.currentThread() returns a reference to the current thread, not the object. So, you should look for reference to the object i.e this keyword.
You wish to have winner as a private member. You can't change it from run() in another class. So, you can pass the current object from run() as an argument to a method in GateMain by this.
You can edit the done() method as:
synchronized static void done(Gate new_gate){
if(winner == null){
winner = new_gate;
}
}
Replace the line Main.done() with Main.done(this)

Why am I getting different results by 2 Threads even that my method is synchronized?

This is the code I am running:
public class MyRunnableClass implements Runnable {
static int x = 30;
int y = 0;
#Override
public void run() {
for(int i=0;i<30;i++){
getFromStash();
}
}
public synchronized void getFromStash(){
x--;
y++;
}
}
and my Test class:
public class MyRunnableClassTest {
public static void main(String[] args){
MyRunnableClass aa = new MyRunnableClass();
MyRunnableClass bb = new MyRunnableClass();
Thread a = new Thread(aa);
Thread b = new Thread(bb);
a.start();
b.start();
System.out.println(aa.y);
System.out.println(bb.y);
}
}
Sometimes I see output:
30
30
and sometimes I see:
30
0
Why? The method I have, is synchronized?
I actually expect to see something like 15 - 15 but it is definetly not what I am getting.
You need to wait for the threads to finish.
a.start();
b.start();
a.join();
b.join();
System.out.println(aa.y);
System.out.println(bb.y);
At that point you should see predictable results.
Added
Now you've had a chance to play - here's my attempt at what you seem to be trying to do.
public class MyRunnableClass implements Runnable {
static AtomicInteger stash = new AtomicInteger(1000);
int y = 0;
#Override
public void run() {
try {
while (getFromStash()) {
// Sleep a little 'cause I'm on a single-core machine.
Thread.sleep(0);
// Count how much of the stash I got.
y += 1;
}
} catch (InterruptedException ex) {
System.out.println("Interrupted!");
}
}
public boolean getFromStash() {
// It must be > 0
int was = stash.get();
while (was > 0) {
// Step down one.
if (stash.compareAndSet(was, was - 1)) {
// We stepped it down.
return true;
}
// Get again - we crossed with another thred.
was = stash.get();
}
// Must be 0.
return false;
}
}
Remove the bb and use only the aa object to create the two threads.
It's synchronized on this and you use two different objects (i.e. this values) - aa and bb. So practically you defeat the whole synchronization idea by using the two different objects.
Thread a = new Thread(aa);
Thread b = new Thread(aa);
a.start();
b.start();
Alternatively, you can do something like this.
public class MyRunnableClass implements Runnable {
private static final Object lock = new Object();
static int x = 30;
int y = 0;
#Override
public void run() {
for(int i=0;i<30;i++){
getFromStash();
}
}
public void getFromStash(){
synchronized(lock){
x--;
y++;
}
}
}
Here is what I think you want to achieve.
class Stash {
private int x = 30;
private int y = 0;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public synchronized void getFromStash(){
System.out.println("Method getFromStash called by " + Thread.currentThread().getName() + ".");
x--;
y++;
}
}
public class MyRunnableClass implements Runnable {
private Stash st = null;
private volatile boolean done = false;
public MyRunnableClass(Stash st){
this.st = st;
}
#Override
public void run() {
for(int i=0;i<30;i++){
this.st.getFromStash();
try {
double m = Math.random();
Thread.sleep((long)((m + 1) * 100.0));
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
System.out.println("Thread ---> " + Thread.currentThread().getName() + " finished!");
this.done = true;
}
public static void main(String[] args) throws Exception {
Stash st = new Stash();
MyRunnableClass aa = new MyRunnableClass(st);
MyRunnableClass bb = new MyRunnableClass(st);
Thread a = new Thread(aa);
Thread b = new Thread(bb);
a.setName("Thread A");
b.setName("Thread B");
a.start();
b.start();
while (true){
System.out.println(st.getX() + " " + st.getY());
Thread.sleep(10);
if (aa.done && bb.done) break;
}
System.out.println("Main thread finished too!");
}
}
Since you print the values right after you start the threads, you're not going to "catch" the threads in the middle of the for loops. The thread scheduler is returning control to the main thread sometimes after the threads are done and sometimes before they start, but never during run(). You have to wait until the threads are done.
As you've already figured out, your first attempt didn't work the way you wanted because 1) you weren't waiting for the threads to finish, so sometimes you read the values before they'd done their work, and 2) you're not looking for each thread to pull from the stash 30 times, but rather for the sum total of the pulls to be 30 (divided among the threads however it happens).
Your move to stopping each thread when x > 0 instead of after N pulls is the right approach, but the test for whether x > 0 (and therefore whether to continue) needs to be synchronized as well. Otherwise you could test the value and find that x == 1, decide to do a pull, and then before you actually do it the other thread takes the last one. Then you do your pull, leaving x at -1 and the sum of the two y's at 31.
To solve this, you either need to put a check for x > 0 within the synchronized getFromStash() method (so you don't actually change x and y unless it's safe to do so), or you need to expose the lock outside the Stash object from peter.petrov's answer, so that both threads can explictly synchronize on that object when they test x > 0 and then call getFromStash() if applicable.
Also, it's generally much harder to figure out thread synchronization when you're using static variables; there tend to be interactions you don't anticipate. You're much better off creating a separate object (e.g. peter.petrov's Stash class) to help you represent the pool, and the pass a reference to it to each of your thread classes. That way all access is via non-static references, and you'll have an easier time making sure you get the code right.

Issues with using too many Threads a benchmark program

I've programmed a (very simple) benchmark in Java. It simply increments a double value up to a specified value and takes the time.
When I use this singlethreaded or with a low amount of threads (up to 100) on my 6-core desktop, the benchmark returns reasonable and repeatable results.
But when I use for example 1200 threads, the average multicore duration is significantly lower than the singlecore duration (about 10 times or more). I've made sure that the total amount of incrementations is the same, no matter how much threads I use.
Why does the performance drop so much with more threads? Is there a trick to solve this problem?
I'm posting my source, but I don't think, that there is a problem.
Benchmark.java:
package sibbo.benchmark;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
public class Benchmark implements TestFinishedListener {
private static final double TARGET = 1e10;
private static final int THREAD_MULTIPLICATOR = 2;
public static void main(String[] args) throws InterruptedException {
Benchmark b = new Benchmark(TARGET);
b.start();
}
private int coreCount;
private List<Worker> workers = new LinkedList<>();
private List<Worker> finishedWorkers = new LinkedList<>();
private double target;
public Benchmark(double target) {
this.target = target;
getSystemInfos();
printInfos();
}
private void getSystemInfos() {
coreCount = Runtime.getRuntime().availableProcessors();
}
private void printInfos() {
System.out.println("Usable cores: " + coreCount);
System.out.println("Multicore threads: " + coreCount * THREAD_MULTIPLICATOR);
System.out.println("Loops per core: " + new DecimalFormat("###,###,###,###,##0").format(TARGET));
System.out.println();
}
public synchronized void start() throws InterruptedException {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
System.out.print("Initializing singlecore benchmark... ");
Worker w = new Worker(this, 0);
workers.add(w);
Thread.sleep(1000);
System.out.println("finished");
System.out.print("Running singlecore benchmark... ");
w.runBenchmark(target);
wait();
System.out.println("finished");
printResult();
System.out.println();
// Multicore
System.out.print("Initializing multicore benchmark... ");
finishedWorkers.clear();
for (int i = 0; i < coreCount * THREAD_MULTIPLICATOR; i++) {
workers.add(new Worker(this, i));
}
Thread.sleep(1000);
System.out.println("finished");
System.out.print("Running multicore benchmark... ");
for (Worker worker : workers) {
worker.runBenchmark(target / THREAD_MULTIPLICATOR);
}
wait();
System.out.println("finished");
printResult();
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
private void printResult() {
DecimalFormat df = new DecimalFormat("###,###,###,##0.000");
long min = -1, av = 0, max = -1;
int threadCount = 0;
boolean once = true;
System.out.println("Result:");
for (Worker w : finishedWorkers) {
if (once) {
once = false;
min = w.getTime();
max = w.getTime();
}
if (w.getTime() > max) {
max = w.getTime();
}
if (w.getTime() < min) {
min = w.getTime();
}
threadCount++;
av += w.getTime();
if (finishedWorkers.size() <= 6) {
System.out.println("Worker " + w.getId() + ": " + df.format(w.getTime() / 1e9) + "s");
}
}
System.out.println("Min: " + df.format(min / 1e9) + "s, Max: " + df.format(max / 1e9) + "s, Av per Thread: "
+ df.format((double) av / threadCount / 1e9) + "s");
}
#Override
public synchronized void testFinished(Worker w) {
workers.remove(w);
finishedWorkers.add(w);
if (workers.isEmpty()) {
notify();
}
}
}
Worker.java:
package sibbo.benchmark;
public class Worker implements Runnable {
private double value = 0;
private long time;
private double target;
private TestFinishedListener l;
private final int id;
public Worker(TestFinishedListener l, int id) {
this.l = l;
this.id = id;
new Thread(this).start();
}
public int getId() {
return id;
}
public synchronized void runBenchmark(double target) {
this.target = target;
notify();
}
public long getTime() {
return time;
}
#Override
public void run() {
synWait();
value = 0;
long startTime = System.nanoTime();
while (value < target) {
value++;
}
long endTime = System.nanoTime();
time = endTime - startTime;
l.testFinished(this);
}
private synchronized void synWait() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You need to understand that the OS (or Java thread scheduler, or both) is trying to balance between all of the threads in your application to give them all a chance to perform some work, and there is a non-zero cost to switch between threads. With 1200 threads, you have just reached (and probably far exceeded) the tipping point wherein the processor is spending more time context switching than doing actual work.
Here is a rough analogy:
You have one job to do in room A. You stand in room A for 8 hours a day, and do your job.
Then your boss comes by and tells you that you have to do a job in room B also. Now you need to periodically leave room A, walk down the hall to room B, and then walk back. That walking takes 1 minute per day. Now you spend 3 hours, 59.5 minutes working on each job, and one minute walking between rooms.
Now imagine that you have 1200 rooms to work in. You are going to spend more time walking between rooms than doing actual work. This is the situation that you have put your processor into. It is spending so much time switching between contexts that no real work gets done.
EDIT: Now, as per the comments below, maybe you spend a fixed amount of time in each room before moving on- your work will progress, but the number of context switches between rooms still affects the overall runtime of a single task.
Ok, I think I've found my problem, but until now, no solution.
When measuring the time every thread runs to do his part of the work, there are different possible minimums for different total amounts of threads. The maximum is the same everytime. In case that a thread is started first and then is paused very often and finishes last. For example this maximum value could be 10 seconds. Assuming that the total amount of operations that is done by every thread stays the same, no matter how much threads I use, the amount of operations that is done by a single thread has to be changed when using a different amount of threads. For example, using one thread, it has to do 1000 operations, but using ten threads, everyone of them has to do just 100 operations. Now, using ten threads, the minimum amount of time that one thread can use is much lower than using one thread. So calculating the average amount of time every thread needs to do his work is nonsense. The minimum using ten Threads would be 1 second. This happens if one thread does its work without interruption.
EDIT
The solution would be to simply measure the amount of time between the start of the first thread and the completion of the last.

Using threads and recursion in Java to calculate Fibonacci numbers

I'm relatively new in the Java world and I have a problem which I don't understand.
I have a Class (to get the fibonacci row):
class Fib {
public static int f(int x){
if ( x < 2 )
return 1;
else
return f(x-1)+ f(x-2);
}
}
The task now is to start f(x-1) and f(x-2) each in a separate Thread.
One time with implementing the Thread class and the other with implementing Runnable.
As you probably know, it's an exercise from my prof.
I know how to start a Thread in Java and I know how this whole Thread thing theoretically works, but I can't find a solution for starting separate Threads in this recursive function.
What has to be done in the run function?
Probably
public void run(){
//int foo=start f(this.x-1)
//int bar=start f(this.x-2)
//return foo+bar?
}
And how can I paste x in my runnable function?
Is x passed into the object at creation?
Class Fib ...{
int x;
public ... run ...
public ... f(x)....
}
in the main method
(new Fib(x)).start();
Or am I on a totally wrong path?
For this to work, you need 1) a way to pass the number into the new thread, 2) to start the thread, 3) to wait for the thread to finish, and 4) a way to get the result back from the thread.
You can pass in the number through the constructor. You can have a public data member called "answer" to contain the result of the computation. Starting the thread can be done with the start() method, and the join() method waits for the thread to complete.
The following example demonstrates this. That should be a good starting point; from here you can abstract away some of the messiness to get a better API as desired.
public class Fib extends Thread
{
private int x;
public int answer;
public Fib(int x) {
this.x = x;
}
public void run() {
if( x <= 2 )
answer = 1;
else {
try {
Fib f1 = new Fib(x-1);
Fib f2 = new Fib(x-2);
f1.start();
f2.start();
f1.join();
f2.join();
answer = f1.answer + f2.answer;
}
catch(InterruptedException ex) { }
}
}
public static void main(String[] args)
throws Exception
{
try {
Fib f = new Fib( Integer.parseInt(args[0]) );
f.start();
f.join();
System.out.println(f.answer);
}
catch(Exception e) {
System.out.println("usage: java Fib NUMBER");
}
}
}
Using threads is usually intended to improve performance. However each thread adds an overhead and if the task performed is small, there can be much more over head than actual work done. Additionally most PCs can only handle about 1000 threads and will hang if you have much more than 10K threads.
In your case, fib(20) will generate 6765 threads, fib(30) creates 832K, fib(40) creates 102M threads, fib(50) creates over 12 trillion. I hope you can see this is not scalable.
However, using a different approach you can calculate fib(1000000) in under one minute.
import java.math.BigInteger;
/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.466557 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
public static void main(String... args) {
int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
long start = System.nanoTime();
BigInteger fibNumber = fib(place);
long time = System.nanoTime() - start;
System.out.println(place + "th fib # is: " + fibNumber);
System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
}
private static BigInteger fib(int place) {
BigInteger a = new BigInteger("0");
BigInteger b = new BigInteger("1");
while (place-- > 1) {
BigInteger t = b;
b = a.add(b);
a = t;
}
return b;
}
}
You've got the right idea about starting threads in the fib function, and about passing x to the object through the constructor; you'll also need to have a way to get the result of the calculation out of the object at the end - I'm sure you can figure that out ;-) The thread-starting procedure you use in fib is just the same way you always start a thread, like (new Fib(x-1)).start() although you might want to save the thread in a variable because you'll need it to get the result of the computation later.
So with the help of you all I managed to do the same thing with implementing runnable instead of using the Thread Class.
Can you all have a look and tell me if thats the way how to do it if the task is to implement runnable.
The Code itself works.
public class Fib implements Runnable
{
private int x;
public int answer;
public Fib(int x) {
this.x = x;
}
public void run() {
if( x < 2 )
answer = 1;
else {
try {
Fib f1= new Fib(x-1);
Fib f2= new Fib(x-2);
Thread threadf1=new Thread(f1);
Thread threadf2=new Thread(f2);
threadf1.start();
threadf2.start();
threadf1.join();
threadf2.join();
answer = f1.answer + f2.answer;
}
catch(InterruptedException ex) { }
}
}
public static void main(String[] args)
{
try {
for (int i=0;i<19;i++){
Fib f= new Fib(i);
Thread threadf= new Thread(f);
threadf.start();
threadf.join();
System.out.println("Ergebnis:"+f.answer);
}
}
catch(Exception e) {
System.out.println("usage: java Fib NUMBER");
}
}
}

Categories

Resources