javaide icon indicating copy to clipboard operation
javaide copied to clipboard

Static int turns into 0 on threads

Open RafaelSilvaFerreira opened this issue 4 years ago • 1 comments

In the following code, totalIngressos should be 100 for the whole ride up to compraIngresso(), but at some point it becomes 0. Tested on PC, code works fine.

//first file package view;

import java.util.concurrent.Semaphore; import controller.ThreadCompra;

public class Main{

public static void main(String[] args) {

Semaphore semaforo = new Semaphore(1);
for (int i = 0; i < 300; i++) {
	int qtd = (int)((Math.random() * 4) + 1);
	Thread t = new ThreadCompra(i, qtd, semaforo);
	t.start();
}

}

} //---------------- end of file

package controller;

import java.util.concurrent.Semaphore;

public class ThreadCompra extends Thread {

private static int totalIngressos = 100;
private int id, qtd;
private Semaphore semaforo;
private boolean liberado;

public ThreadCompra(int id, int qtd, Semaphore semaforo) {
	this.id = id;
	this.qtd = qtd;
	this.semaforo = semaforo;
}

@Override
public void run() {
	login();
	if (liberado) {
		tempoCompra();
		if (liberado) {
			try {
				semaforo.acquire();
				compraIngresso();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				semaforo.release();
			}
		}
	}
}

private void tempoCompra() {
	int tempo = (int) ((Math.random() * 2001) + 1000);
	try {
		Thread.sleep(tempo);
		if (tempo >= 2500) {
			System.out.println("Compra do #"+id+" TimeOut");
			liberado = false;
		} else {
			System.out.println("Comprador #" + id + " solicitou a compra");
			liberado = true;
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

private void login() {
	int tempo = (int) ((Math.random() * 1951) + 50);
	try {
		Thread.sleep(tempo);
		if (tempo >= 1000) {
			System.out.println("Login do #"+id+" TimeOut");
			liberado = false;
		} else {
			System.out.println("Comprador #" + id + " logado no sistema");
			liberado = true;
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

private void compraIngresso() {
	if (totalIngressos - qtd >= 0) {
		totalIngressos -= qtd;
		System.out.println("Comprador #" + id + " comprou seus " + qtd
				+ " ingressos");
		System.out.println("Sobraram "+totalIngressos+" ingressos");
	} else {
		System.out.println("Comprador #" + id + " não comprou seus " + qtd
				+ " ingressos por indisponibilidade da quantidade");
	}
}

}

RafaelSilvaFerreira avatar Sep 18 '20 16:09 RafaelSilvaFerreira

Its a dead project. Last commit is 2 years ago

Malaska678 avatar Sep 19 '20 09:09 Malaska678