Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.concurrent.*;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author francisco
- */
- public class exer2 implements Runnable {
- String filename;
- Semaphore s;
- Semaphore s2;
- SharedCounter share;
- public exer2(Semaphore sem, Semaphore sem2, String filename, SharedCounter counter) {
- s = sem;
- s2 = sem2;
- this.filename = filename + ".txt";
- share = counter;
- }
- public void writeOnFile(int num) {
- int counter = share.getCounter();
- if (counter <= 10) {
- try {
- String text = ("Thread " + Thread.currentThread().getName() + " escreveu " + num + "x. Counter: " + counter + "\n");
- BufferedWriter writer = new BufferedWriter(new FileWriter(this.filename, true));
- writer.append(text);
- writer.close();
- System.out.println(text);
- Thread.sleep(1000);
- } catch (IOException ex) {
- } catch (InterruptedException ex) {
- }
- }
- }
- public void run() {
- System.out.println("Thread " + Thread.currentThread().getName() + " iniciou");
- try {
- s.acquire();
- share.incrementCounter();
- writeOnFile(1);
- s.release();
- } catch (InterruptedException ex) {
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ex) {
- }
- try {
- s2.acquire();
- share.incrementCounter();
- writeOnFile(2);
- s2.release();
- } catch (InterruptedException ex) {
- }
- }
- public static void main(String args[]) {
- String filename = args[0];
- SharedCounter share = new SharedCounter();
- Semaphore sem = new Semaphore(1);
- Semaphore sem2 = new Semaphore(1);
- for (int i = 0; i < 20; i++) {
- Thread th = new Thread(new exer2(sem, sem2, filename, share), "Th" + i);
- th.start();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement