Skip to content

Instantly share code, notes, and snippets.

@Da9el00
Created November 19, 2023 20:02
Show Gist options
  • Save Da9el00/461df0ff63593a5d7761ff069854d653 to your computer and use it in GitHub Desktop.
Save Da9el00/461df0ff63593a5d7761ff069854d653 to your computer and use it in GitHub Desktop.
Java sender receiver using multithreading
public class Data {
private String packet;
// True: receiver waits
// False: sender waits
private boolean transfer = true;
public synchronized String receive() {
while (transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = true;
notifyAll();
return packet;
}
public synchronized void send(String packet) {
while (!transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread Interrupted");
}
}
this.packet = packet;
transfer = false;
notifyAll();
}
}
public class Main {
public static void main(String[] args) {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
}
}
public class Receiver implements Runnable {
private final Data load;
public Receiver(Data load) {
this.load = load;
}
public void run() {
// Keep receiving messages until "End" is received
while (true) {
String receivedMessage = load.receive();
if ("End".equals(receivedMessage)) {
break;
}
System.out.println(receivedMessage);
}
}
}
public class Sender implements Runnable {
private final Data data;
public Sender(Data data) {
this.data = data;
}
public void run() {
List<String> packets = List.of(
"First packet",
"Second packet",
"Third packet",
"Fourth packet",
"End");
packets.forEach(data::send);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment