I have 2 threads that can communicate with each other in the console(like a chat among each other). The thread only can send messages and the messages are user input. I want to send files(Ex: .pdf) among those two threads. How to do it?
In the code below you will find the two thread communication.
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
Chat chat = new Chat();
new Thread1(chat).start();
new Thread2(chat).start();
}
}
class Chat {
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
String str1,str2;
int flag = 2;
public synchronized void getTalk1() throws InterruptedException {
if (flag==1) {
wait();
}
System.out.print("User1: ");
str1 = sc1.nextLine();
if(str1.equalsIgnoreCase("bye")) {
System.out.println("\nUser1 has left the chat. Conversation ended.");
System.exit(0);
}
flag = 1;
notify();
}
public synchronized void getTalk2() throws InterruptedException {
if (flag == 2) {
wait();
}
System.out.print("User2: ");
str2 = sc2.nextLine();
if(str2.equalsIgnoreCase("bye")) {
System.out.println("\nUser2 has left the chat. Conversation ended.");
System.exit(0);
}
flag = 2;
notify();
}
}
//Thread-1 class
class Thread1 extends Thread {
Chat chat;
public Thread1(Chat chat) {
this.chat = chat;
}
public void run() {
try {
while(true) {
chat.getTalk1();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//Thread-2 class
class Thread2 extends Thread {
Chat chat;
public Thread2(Chat chat) {
this.chat = chat;
}
public void run() {
try {
while(true) {
chat.getTalk2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
This is the output on 2 thread communication : 2 threads communication