I’ll help you post the code:
import java.util.Scanner;
public class Main {
static class SharedData{
public int a,b;
//
//
// public int getA() {
// return a;
// }
//
// public void setA(int a) {
// this.a = a;
// }
//
// public int getB() {
// return b;
// }
//
// public void setB(int b) {
// this.b = b;
// }
}
static class ThreadOne extends Thread{
final SharedData sharedData;
public ThreadOne(SharedData sharedData){
this.sharedData = sharedData;
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
while (true){
synchronized (sharedData){
System.out.print("Enter the first number: ");
int t = scanner.nextInt();
sharedData.a=t;
System.out.print("Enter the second number: ");
t = scanner.nextInt();
sharedData.b=t;
try {
sharedData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
sharedData.notify();
}
}
}
}
static class ThreadTwo extends Thread{
final SharedData sharedData;
public ThreadTwo(SharedData sharedData){
this.sharedData = sharedData;
}
@Override
public void run() {
while(true){
synchronized (sharedData){
try {
sharedData.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Addition Result: "+(sharedData.a+sharedData.b));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sharedData.notify();
}
}
}
}
public static void main(String[] args) {
SharedData sharedData = new SharedData();
ThreadOne t1 = new ThreadOne(sharedData);
ThreadTwo t2 = new ThreadTwo(sharedData);
t1.start();
t2.start();
}
}
Bất cứ action nào mà có interact with user thì phải chạy trên main thread, vd: user input, user vẽ, etc. Sau khi lấy được input rồi mới tạo 1 thread chạy background, suggest nhiêu đây là bạn đủ hiểu rồi.