Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Semaphore{
- private int i = 0;
- public synchronized void take(){
- i++;
- while(i > 1){
- try{
- wait();
- } catch (Exception e){
- errors++;
- }
- }
- }
- public synchronized void release(){
- i = 0;
- this.notify();
- }
- }
- public class Worker extends Thread{
- private Semaphore semaphore;
- private int count;
- public Worker(int c,Semaphore semaphore){
- count = (c == 1 ? 1 : 0);
- this.semaphore = semaphore;
- }
- public void write(Template template){
- try{
- Path path = Paths.get(filepath);
- byte[] bytes = Files.readAllBytes(path);
- ByteArrayInputStream in = new ByteArrayInputStream(bytes);
- ObjectInputStream is = new ObjectInputStream(in);
- ArrayList<Template> arrayList =(ArrayList<Template>) is.readObject();
- arrayList.add(template);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream os = new ObjectOutputStream(out);
- os.writeObject(arrayList);
- Files.write(path,out.toByteArray());
- } catch (Exception e){
- System.out.println("Thread - " + (count % 2) + " : " + count);
- e.printStackTrace();
- } finally {
- semaphore.release();
- }
- }
- public void run(){
- while(count < arrayList.size()){
- semaphore.take();
- write(arrayList.get(count));
- count+=2;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement