I hope getting helped, because I have been trying to understand this program for 3 days. The essence of the program is the implementation of methods for pausing, resuming and stopping the flow. Code taken from Herbert Schildt’s Beginner’s Book, 9th Edition. Chapter 12. I didn’t write it exactly, but I think the essence is clear.
`
class MyThread implements Runnable{
Thread thrd;
boolean suspended;
boolean stopped;
MyThread(String name){
thrd= new Thread(this,name);
suspended=false;
stopped=false;
}
public static MyThread createAndStart(String name){
MyThread mt = new MyThread(name);
mt.thrd.start();
return mt;
}
public void run(){
try{
for(int i=1;i<1000;i++){
System.out.print(i + " ");
if(i%10==0){
System.out.println();
Thread.sleep(250);
}
synchronized(this){
while(suspended) wait();
if(stopped) break;
}
}
}
catch(InterruptedException e){
}
}
synchronized void myStop(){
stopped=true;
suspended=false;
notify();
}
synchronized void mySuspend(){
suspended = true;
}
synchronized void myResume(){
suspended=false;
notify();
}
}
public class Suspend {
public static void main(String[] args){
MyThread mt1 = MyThread.createAndStart("Thread 1");
try{
Thread.sleep(1000);
mt1.mySuspend();
Thread.sleep(1000);
mt1.myResume();
Thread.sleep(1000);
mt1.mySuspend();
Thread.sleep(1000);
mt1.myResume();
Thread.sleep(1000);
mt1.mySuspend();
mt1.myStop();
}
catch(InterruptedException e){
}
}
}`
Now to my questions:
- my brain refuses to understand the synchronized(this) construction. Why is it needed if the methods are already synchronized? And what are we synchronizing in this block? While and if statements???
- why is Thread.sleep() used in the main method if the essence of synchronization is for threads to automatically gain access to the object?
- In the book, in previous exercises, a separate class was usually created, and through its methods the threads would already do their jobs, but in this program, the class itself is used for this, which implements the Runnable interface. What the hell is this anyway??! I would be very grateful for clarifications
Btw sorry for bad English. Pls ask if you don’t understand something from my letter.
Tried chatgpt to explain this code to me, but it’s explanation is nonsense
Амир Турпуханов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.