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);
		}
	}
}

Recommended Answers

All 5 Replies

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

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?

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");

?

^ because SleepThread is a Runnable not a Thread, so that's how you create a new Thread for it?

ah, ok, my bad :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.