Create two threads to print alternately 1-100

\u674e\u80b2\u6b22 2021-11-25 14:36:54

Problem description

Create two threads to print alternately 1-100

Ideas

Threads 1 Get into run(), Finish printing and count++ operation , call wait() Method release lock , Threads 2 Get into run(),notifyAll() Wake up the thread 1 And get the lock , Finish printing and count++ operation , call wait() Release the lock , repeat …

Code implementation

public class Create two threads to print alternately 1 To 100 implements Runnable{

public int count = 1;
@Override
public void run() {

while(true){

synchronized (this){

notifyAll();
if(count <= 100){

System.out.println(Thread.currentThread().getName()+":"+count);
count++;
try{

wait();
}catch(InterruptedException e){

e.printStackTrace();
}
}else{

return;
}
}
}
}
}
public class Test class {

public static void main(String[] args) {

Create two threads to print alternately 1 To 100 res = new Create two threads to print alternately 1 To 100();
Thread thread1 = new Thread(res);
Thread thread2 = new Thread(res);
thread1.setName(" Threads 1");
thread2.setName(" Threads 2");
thread1.start();
thread2.start();
}
}

Running results :
 Insert picture description here

Please bring the original link to reprint ,thank
Similar articles