Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. public class Semaphore{
  2. private int i = 0;
  3. public synchronized void take(){
  4. i++;
  5. while(i > 1){
  6. try{
  7. wait();
  8. } catch (Exception e){
  9. errors++;
  10. }
  11. }
  12. }
  13. public synchronized void release(){
  14. i = 0;
  15. this.notify();
  16. }
  17. }
  18. public class Worker extends Thread{
  19. private Semaphore semaphore;
  20. private int count;
  21. public Worker(int c,Semaphore semaphore){
  22. count = (c == 1 ? 1 : 0);
  23. this.semaphore = semaphore;
  24. }
  25. public void write(Template template){
  26. try{
  27. Path path = Paths.get(filepath);
  28. byte[] bytes = Files.readAllBytes(path);
  29. ByteArrayInputStream in = new ByteArrayInputStream(bytes);
  30. ObjectInputStream is = new ObjectInputStream(in);
  31. ArrayList<Template> arrayList =(ArrayList<Template>) is.readObject();
  32. arrayList.add(template);
  33. ByteArrayOutputStream out = new ByteArrayOutputStream();
  34. ObjectOutputStream os = new ObjectOutputStream(out);
  35. os.writeObject(arrayList);
  36. Files.write(path,out.toByteArray());
  37. } catch (Exception e){
  38. System.out.println("Thread - " + (count % 2) + " : " + count);
  39. e.printStackTrace();
  40. } finally {
  41. semaphore.release();
  42. }
  43. }
  44. public void run(){
  45. while(count < arrayList.size()){
  46. semaphore.take();
  47. write(arrayList.get(count));
  48. count+=2;
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement