Threads in Java
Posted
by owca
on Stack Overflow
See other posts from Stack Overflow
or by owca
Published on 2010-05-26T17:32:10Z
Indexed on
2010/05/26
17:41 UTC
Read the original article
Hit count: 296
I've created simple program to test Threads in Java. I'd like it to print me numbers infinitely, like 123123123123123. Dunno why, but currently it stops after one cycle finishing 213 only. Anyone knows why ?
public class Main {
int number;
public Main(int number){
}
public static void main(String[] args) {
new Infinite(2).start();
new Infinite(1).start();
new Infinite(3).start();
}
}
class Infinite extends Thread {
static int which=1;
static int order=1;
int id;
int number;
Object console = new Object();
public Infinite(int number){
id = which;
which++;
this.number = number;
}
@Override
public void run(){
while(1==1){
synchronized(console){
if(order == id){
System.out.print(number);
order++;
if(order >= which){
order = 1;
}
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
else {
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
}
try{Thread.sleep(0);} catch(Exception e) {}
}
}
}
© Stack Overflow or respective owner