Illegela thread operation...?

Hello,

I have a class like that:

class Sampleimplements Runnable{

privateint x = 0;

publicsynchronizedvoid run(){

for (int i=0;i<10;i++){

try{

Thread.sleep(100);

}catch (InterruptedException ex){

}

x++;

System.out.println(Thread.currentThread().getName() +" : " + x);

}

}

}

And I consume this class like that:

Sample s =new Sample();

Thread t1 =new Thread(s);

t1.setName("First");

Thread t2 =new Thread(s);

t2.setName("Second");

System.out.println("STARTING");

t1.start();

t2.start();

t2.join();

System.out.println("END");

When I execute this code, I sometimes get this error:

java.lang.IllegalThreadStateException

at java.lang.ThreadGroup.add(ThreadGroup.java:846)

at java.lang.Thread.start(Thread.java:596)

What is the wrong with the threads that I create?

Thanks in advance...

[1841 byte] By [xyzta] at [2007-11-26 20:00:06]
# 1
You can't reuse a same Runnable object among multiple threads. Make different instances for each thread.
hiwaa at 2007-7-9 22:57:24 > top of Java-index,Core,Core APIs...
# 2
> You can't reuse a same Runnable object among multiple> threads. Make different instances for each thread.That is incorrect. You can pass the same Runnable to as many threads as you like. Whether that makes sense or will work correctly depends on what the Runnable
davidholmesa at 2007-7-9 22:57:24 > top of Java-index,Core,Core APIs...
# 3

> Sample s = new Sample();

> Thread t1 = new Thread(s);

> t1.setName("First");

> Thread t2 = new Thread(s);

> t2.setName("Second");

> System.out.println("STARTING");

> t1.start();

> t2.start();

> t2.join();

> System.out.println("END");

>

> When I execute this code, I sometimes get this

> error:

> java.lang.IllegalThreadStateException

You get this when you try to start a Thread that has already been started. Check your real code against what you wrote here.

davidholmesa at 2007-7-9 22:57:24 > top of Java-index,Core,Core APIs...