Variable synchronization in multiple Java Threads

Asked

Viewed 35 times

0

Hello.
My question is how to use the block Synchronized, my class Fileadapter has a method write who receives the Inputstream from the result of an HTTP connection I’m using to download a file, every Kilobyte downloaded and written to disk, it calls the method downloaded of the class instance Downloadreport that he received, to pass on what has already been downloaded.

In one another Thread, that is printing the output to the user, it calls the method updateProgress, also of class Downloadreport, this method is responsible for updating a progress bar that is displayed to the user in the terminal.

The problem will be whether the class Fileadapter try to update the amount of bytes downloaded right at the time Thread Exit try to update the progress bar, as both methods edit the variable value intermediateDownloaded, which only works as an auxiliary variable, to hold the amount of bytes downloaded since the last update, to calculate the download speed.

If I use the block "Synchronized (this)", within the methods downloaded and updateProgress, it will block the whole class Downloadreport, and the Thread output will only be able to update the progress bar after the class Fileadapter update the amount of bytes downloaded?

Fileadapter:

    public void write(InputStream content, DownloadReport downloadReport) throws IOException {

        FileOutputStream output = new FileOutputStream(file);

        byte[] buffer = new byte[1024];

        int read;

        while ((read = content.read(buffer)) != -1) {
            output.write(buffer, 0, read);
            downloadReport.downloaded(read);
        }
    }

Downloadreport:

    public void downloaded(int bytes) {
        intermediateDownloaded += bytes;
        downloaded += bytes;
    }

    public void updateProgress() {

        long now = System.currentTimeMillis();
        double delta = UnitHelper.sizeRound(((now - lastTimeUpdate) / 1000.0), 2);

        if (delta >= 1) {
            unitAdapter.convertSpeed(intermediateDownloaded, delta);

            intermediateDownloaded = 0;
            lastTimeUpdate = now;
        }

        progressBar.updateProgress(unitAdapter.finalSize,
                unitAdapter.recalculate(downloaded), unitAdapter.unity);
    }

1 answer

0


Look if it helps you:

Thread execucao = new Thread(() -> {
    synchronized (this) {
        try {
            processo.executar(quantum);
        } catch (InterruptedException e) {
            System.out.println("Thread Interrompida!");
        }
        notify();
    }
});
execucao.start();
synchronized (execucao) {
    execucao.wait();
}

I don’t know how to work threads very well, but that’s how I solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.