Question:
I make my first consultation available and I thank in advance for future responses.
To start I have a form that contains 2 jcombobox
:
jcbSerie
and jcbPartido
.
The form integrates
Runnable()
In the form variables I have a Thread
and an int
:
Thread Serie = new Thread();
int opt = 1;
When initializing the form, the following is executed:
Serie.start();
I initialize it with start()
because it informs me that the difference with run()
is that it runs asynchronously. In the fragment run()
<= execution method , there is the code to execute which has the following format:
@Override
public void run() {
switch (opt) {
case 1:
MetodoEjecutado1();
break;
case 2:
MetodoEjecutado2();
break;
case 3:
break;
}
}
So, as expected, conditional 1 is executed when the form is executed. But my query is the following: How or what is the way in which I should execute the conditional 2 of the run()
from jcbPartido
. To be more precise :
Execute the ExecutedMethod1 () only once and that the thread is no longer available or destroy it (I am new, I am willing to read the answers);
In the jcbSerie item change event if you select a different value than the option "Select option" unlocks the jcbPartido jcombobox.
When changing the item in jcbPartido, the variable
opt
that is worth 1 changes toopt = 2
, so how can I execute the run () method that only executes once asynchronously ExecutedMethod2 (), and like the first part, it dies or stops the finish.
Thank you very much for your time!.
Answer:
I see 2 solutions to your problem. A simple but inelegant:
@Override
public void run() {
try {
while(true){
switch (opt) {
case 1:
MetodoEjecutado1();
opt = 3;
break;
case 2:
MetodoEjecutado2();
opt = 3;
break;
case 3:
//Espera indefinidamente a una modificación externa de opt.
sleep(100);
break;
}
}
}catch(InterruptedException e){
//exception necesaria del sleep.
e.printStackTrace();
}
}
In this way, you only have to create an instance of the String class and start the Thread. If it is necessary to stop the thread, you can do it at any time with Serial.interrupt ();
And a second solution that forces the programmer to create new instances of the Thread every time he wants to execute it, but it is cleaner.
The run () code can only be started once per instance. After the instructions inside run () are finished, the Thread is automatically interrupted.
In this way, you could instantiate String, decide which option you want to execute, and call the String.start () method;
If you are working with Threads i Swing I recommend you investigate this post and this oracle article.