The right way of using threads
Hi!
I have just started using threads and... confused myself :D
This is what I am trying to do:
- start the first thread, if level is 0 then level++, start another new thread, print out a counter every 1 second ,level++ every 5 seconds.
- in the newly created second thread it should print out a second counter and that counter should go faster and faster every 5 seconds (based on the level variable that is set by the first thread).
But what happens is it goes into the first thread and then it goes into the second thread and totally ignores the first thread/first counter.
So my guess is I am doing this completely wrong / using threads wrong.
Advise please!
my code:
Code:
int levelCounter=0;
int secondThreadTime;
public void secondThread(){
int j=0;
Thread secThread = new Thread(this);
while(true){
try {secThread.sleep(secondThreadTime-(levelCounter*100));System.out.println("--"+j+"-"+levelCounter+"-");}
catch(InterruptedException e){};
j++;}
}
public void run()
{int i=0;
while (true)
{
System.out.print(""+i);
updateCounter();
//label1.setText(""+i);
try {Thread.sleep(1000);}
catch(InterruptedException e){};
i++;
if(levelCounter<=0){
levelCounter++;
secondThreadTime=1000;
secondThread();
}
if(i % 5 == 0){levelCounter++;System.out.println("*"+levelCounter+"*");}
}
}