0

Hi everybody.

I have a question: My code produces only 1's. Does it show that processor can only do one task at a time or it is just simply becouse I made something wrong?

import java.lang.Thread;

public class SleepThread implements Runnable{
	
	public final int sleepTime = 1000;
	public String str = new String();
	
	public SleepThread(String name) {
		str=name;
	}
	public void run() {
		try {
		Thread.sleep(sleepTime);
		}
		catch(InterruptedException e) {
			System.out.println("Thread was interrupted");
		}
	}
	public static void main(String[] args) {
		Thread task1 = new Thread(new SleepThread("task1"));
		
		task1.start();
		while(task1.isAlive()) {
			int i=0;
			i++;
			System.out.println(i);
		}
	}
}
4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by stultuske
0

int i = 0; shouldn't be in the loop, try placing it in line 21

Thanks a lot! now it works! so simple, i'm embarased =))
But why I get different numbers every time?

0

what do you mean by different numbers?
and why do you do this:

Thread task1 = new Thread(new SleepThread("task1"));

instead of

SleepThread task1 = new SleepThread("task1");

?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.