Chciałbym wykonać symulator dostępu do medium transmisyjnego. W skrócie dostęp do medium ma wiele osób, ale tylko jedna osoba może w jednym czasie coś wysyłać. Medium ma swoje opóźnienie. Gdy dwie osoby zaczną wysyłać jakieś dane muszą wysłać je ponownie.
Program tworze na wątkach... W tym mam problem nie wiem jak je zsynchronizować...

 package zad2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Cable {
	private long wait;
	private PrintWriter out;
	private boolean open = true;
	private boolean colizion = false;
	private int users = 0;
	
	public Cable(long wait, String output) throws FileNotFoundException{
		this.wait=wait;
		out = new PrintWriter(new File(output));
	}
	synchronized public void write(String s){
		out.println(s);
		out.flush();
	}
	
	public boolean isOpen(){
		return open;
	}
	synchronized public void addUser(){
		if(++users>0)
			open=false;
		if(users>1)
			colizion = true;
	}
	
	synchronized public void degUser(){
		if(--users==0){
			colizion = false;
			open = true;
		}
	}
	
	
	public boolean startMessage(int who, long what) throws InterruptedException{
		write(who + " start send ");
		Thread.sleep(wait);
		if(continueMessage(who,what)){
			Thread.sleep(wait);
			
			return endMessage(who);
		}
			
		else
			return false;
	}
	
	public synchronized boolean continueMessage(int who, long what){
		addUser();
		if(!colizion){
			write(who + " send  "+ what +" "+ users);
			return true;
		}else{
			degUser();
			write(who + " error send");
			return false;
		}
	}
	
	public synchronized boolean endMessage(int who) throws InterruptedException{
		if(!colizion){
			write(who + " END   send !!!!");
			degUser();
			return true;
		}
		write(who + " error send");
		degUser();
		return false;
	}
}
package zad2;

import java.util.Random;

public class Host extends Thread {
	private int number;
	private Cable cable;
	private int ratio=1;
	private long wait;
	private long mess;
	private Random gen = new Random();
	
	public Host(Cable cable, int number, long wait){
		this.cable = cable;
		this.number = number;
		this.wait=wait;
		mess = gen.nextLong();
	}
	public void run(){
		while(true){
			
			while(!cable.isOpen()){
				long w = Math.abs((long) (gen.nextLong() % (wait*ratio)));
				try {
					sleep(w);
				} catch (InterruptedException e) {}
			}
			try {
				if(cable.startMessage(number, mess)){
					break;
				}
			} catch (InterruptedException e) {}
			ratio +=1;
		}
	}
}
 
package zad2;

import java.io.FileNotFoundException;

public class Zadanie2 {
	private static long waitCable = 10;
	private static long waitHosts = 200;
	private static String out = "Zad2.txt";
	private static int nHost = 100;
	
	public static void main(String argv[]) throws FileNotFoundException{
		Cable cable = new Cable(waitCable,out);
		Host hosts[] = new Host[nHost];
		for(int i=0; i<nHost; ++i){
			hosts[i]=new Host(cable, i, waitHosts);
			hosts[i].start();
		}
	}
}