0
Hello, I need to understand how to get a thread to pause its execution and another thread to start running?
I have the following code snippet:
import java.util.concurrent.Semaphore;
public class AB1AB2 {
public static void main(String[] args) {
Semaphore semaforo = new Semaphore(1);
MutableString ms = new MutableString();
Thread thrd0 = new Thread(new Accumulator(ms, semaforo), "THREAD 0");
Thread thrd1 = new Thread(new Accumulator(ms, semaforo), "THREAD 1");
thrd0.start();
thrd1.start();
try{
thrd0.join();
thrd1.join();
}catch(InterruptedException ie){}
System.out.println(ms.getOrdem());
}
}
This code snippet creates two threads and executes the following classes:
import java.util.concurrent.Semaphore;
public class MutableString {
private String ordem ="";
public String getOrdem() {
return ordem;
}
public void setString(){
Thread teste = Thread.currentThread();
if(teste.getName() == "THREAD 0"){
ordem += "A";
teste.interrupt();
ordem += "a";
}
Thread teste2 = Thread.currentThread();
String teste2Name = Thread.currentThread().getName();
if(teste.getName() == "THREAD 1") {
ordem += "B";
teste2.interrupt();
ordem += "b";
}
}
}
class Accumulator implements Runnable{
private MutableString sharedValue;
private Semaphore semaforo;
private int threadAtual;
public Accumulator(MutableString acc, Semaphore sempahore) {
this.sharedValue = acc;
this.semaforo = sempahore;
}
@Override
public void run() {
try{
semaforo.acquire();
sharedValue.setString();
}catch(InterruptedException e){
e.printStackTrace();
}finally{
semaforo.release();
}
}
}
I’m trying to do the following: The thread0 goes and writes "A" in the variable ordem
class MutableString
And then, I need that after she adds the letter "A", the thread execution stops, and starts running thread1, which will add "B" to the String order, right after Thread0 comes back and writes "a" and right after thread1 comes back and writes "b", ending the strig order with: "Abab", tried to use interrupted
, but I was unsuccessful
I don’t know if that would be ideal, but you’ve tried using the
sleep()
?– Sabão
@Soap I tried, I used Sleep for the thread0, but it just sits there waiting, as I do to run thread1, while thread0 is sleeping?
– Jeff Henrique