I have been given the task of running two threads one using extends and one using implements runnable, the output is meant to be similair to this
F(0)
F(1)
F(2)
.........
S(0)
S(1)
S(2)
So far im getting
F(0)
S(1)
F(1)
F(2)
S(2)
public class Fast implements Runnable
{
/** Creates a new instance of Fast */
public void run()
{
for(int i = 0; i <= 9; i++)
{
try
{
System.out.println("F("+ i + ")");
Thread.sleep(200);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
and
public class Slow extends Thread
{
/** Creates a new instance of Slow */
public void run()
{
for(int i = 0; i <= 6; i++)
{
try
{
System.out.println("S("+ i + ")");
Thread.sleep(400);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
With the main
public class Main
{
public static void main(String args[])
{
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
s.start();
}
}
It seems like you want to get Slow to run after Fast? Your output is pretty much what i would expect. Eventually F will finish faster (just 2000ms) and S will still be running (2800ms). I'm not what this assignment has got to do with implementing Runnable or extending Thread since they give you the same end-result.
If you want F to finish completely before S you need to join on F first, like this:
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
ft.join();
s.start();
That will wait for ft to complete before even starting S giving you the desired output F1, F2,... S1,S2,...
Related
Today I was trying to learn about memory management in the JVM and I came across the following question: can I mutate a local variable from two threads spawned within the same function?
In Java, if you try something like this the code will not compile, yielding an error with message "local variables referenced from an inner class must be final or effectively final"
public class MyClass {
static void f() throws Exception {
int x = 0;
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 1000; i++) {
x = x + 1;
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 1000; i++) {
x = x - 1;
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(x);
}
public static void main(String args[]) throws Exception {
for(int i = 0; i < 20; i++) {
f();
}
}
}
However the equivalent code in Scala does compile and run without problem (despite maybe race conditions):
def f(): Unit = {
var x = 0
val t1 = new Thread(new Runnable {
override def run(): Unit =
(1 to 1000).foreach(_ => {x = x + 1})
})
t1.start()
val t2 = new Thread(new Runnable {
override def run(): Unit =
(1 to 1000).foreach(_ => {x = x - 1})
})
t2.start()
t1.join()
t2.join()
println(x)
}
(1 to 20).foreach(_ => f())
Why is the behavior different in each case?
In Scala lambdas, and by extension anonymous classes, can capture local variables. The scala.runtime package contains some extra classes for that purpose. They effectively lift the local variable into an instance variable of another class whose instances can be shared: https://github.com/scala/scala/blob/v2.13.3/src/library/scala/runtime/ObjectRef.java
Suppose I have a List which have 2000 values, i want to divide the list of values and and passing to the method concurrently, SO I can increase my performance.
I applied bellow multi thread concept but its also taking 10 Minutes
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 1; i < visitList.size()/2; i = i + 2) {
auditedT1 += accuracyDao.SumOfChartsAudited(visitList.get(i));
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < visitList.size()/2; i = i + 2) {
auditedT2 += accuracyDao.SumOfChartsAudited(visitList.get(i));
}
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
for (int i = visitList.size()/2; i < visitList.size(); i = i + 2) {
auditedT3 += accuracyDao.SumOfChartsAudited(visitList.get(i));
}
}
});
Thread t4 = new Thread(new Runnable() {
public void run() {
for (int i = visitList.size()/2+1; i < visitList.size(); i = i + 2) {
auditedT4 += accuracyDao.SumOfChartsAudited(visitList.get(i));
}
}
});
t.start();
t1.start();
t3.start();
t4.start();
t.join();
t1.join();
t3.join();
t4.join();
To answer your main question, check out java parallel streams. It's only one way to do this but it's fairly straightforward. You can use a map operation to perform the database calls, then a collect to sum them all together.
https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html
There is no guarantee that this will improve performance though. You may have to profile and see where the performance issue really lies. It could be in your database, network, or somewhere else. (assuming you're using a database since there's DAO in your method names)
How to fix this code using multithreading?
It's working but I need to know how to add a thread to this code, I think that this is why the progress bar not updating progressively!
public void copyfile(ActionEvent event){
try {
File fileIn = new File(filepath);
long length = fileIn.length();
long counter = 0;
double r;
double res=(counter/length);
filename=fieldname.getText();
FileInputStream from=new FileInputStream(filepath);
FileOutputStream to=new FileOutputStream("C:\\xampp\\htdocs\\videos\\"+filename+".mp4");
byte [] buffer = new byte[4096];
int bytesRead=0;
while( (r=bytesRead=from.read(buffer))!= 1){
progressbar.setProgress(counter/length);
counter += r*100;
to.write(buffer, 0, bytesRead);
System.out.println("File is loading!!"+(counter/length));
}
from.close();
to.close();
} catch (Exception e) {
progress.setText("upload is finished!!");
}
}
Can you please post any solution, which helps me?
Thanks for all advices.
There is an example of associating a progress bar with progress of a concurrent task in Oracle's JavaFX 8 concurrency documentation.
import javafx.concurrent.Task;
Task task = new Task<Void>() {
#Override public Void call() {
static final int max = 1000000;
for (int i=1; i<=max; i++) {
if (isCancelled()) {
break;
}
updateProgress(i, max);
}
return null;
}
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
I'm trying to remove items from a list until its empty with multithreading.
Code:
public void testUsers() {
final List<User> users = userDao.findAll();
final int availableProcessors = Runtime.getRuntime().availableProcessors() * multiplier;
final List<String> loggingList = Lists.newArrayList();
final List<Integer> sizeChecked = Lists.newArrayList();
int totalSizeChecked = 0;
int sizeList = users.size();
ExecutorService executorService = Executors.newFixedThreadPool(availableProcessors);
for (int i = 0; i < availableProcessors; i++) {
createThread(executorService, users, loggingList, sizeChecked);
}
executorService.shutdown();
try {
// wait for all threads to die
executorService.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException ex) {
}
for (Integer count : sizeChecked) {
totalSizeChecked += count;
}
Assert.assertTrue(totalSizeChecked==sizeList);
}
private void createThread(ExecutorService executorService, final List<User> users,
final Collection<String> loggingList, final List<Integer> sizeChecked) {
executorService.execute(new Runnable() {
#Override
public void run() {
int totalChecked = 0;
while (!users.isEmpty()) {
User user = null;
synchronized (users) {
if (!users.isEmpty()) {
user = users.remove(0);
}
}
totalChecked++;
if (user != null) {
String reason = checkUser(user);
if (reason != null) {
loggingList.add(reason);
}
} else {
LOGGER.info("user is null");
}
}
sizeChecked.add(totalChecked);
}
});
}
Now I was thinking this couldn't be so wrong cause I made the list synchronised for removing the first item.
I'm testing with a multiplier of 6.(on prod it will be lowered to 1-2)
I get this in the email :
The batch was not correctly executed.
Size of accounts that must be checked : 28499. Size of accounts that have been checked: 25869
What do I wrong to get it threadsafe?
List<Integer> sizeChecked is not thread safe. Therefore you cannot add elements in parallel in it.
Synchronize your add operation or use a thread-safe structure. If sizeChecked is just a counter, use an AtomicLong instead and make each thread increment it.
Ihave this piece of code that i need to 'format/indent'.. Can you please suggest a fix?
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // last prime found Date lastprimeModified = new Date(); // when it was found Thread searcher; // background search thread public void init(ServletConfig config) throws ServletException { super.init(config); // always! searcher = new Thread(this); searcher.setPriority(Thread.MIN_PRIORITY); // be a good citizen searcher.start(); } public void run() { // QTTTBBBMMMTTTOOO long candidate = 1000000000000001L; // one quadrillion and one // Begin loop searching for primes while (true) { // search forever if (isPrime(candidate)) { lastprime = candidate; // new prime lastprimeModified = new Date(); // new "prime time" } candidate += 2; // evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try { searcher.sleep(200); } catch (InterruptedException ignored) { } } } private static boolean isPrime(long candidate) { // Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate); for (long i = 3; i <= sqrt; i += 2) { if (candidate % i == 0) return false; // found a factor } // Wasn't evenly divisible, so it's prime return true; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); if (lastprime == 0) { out.println("Still searching for first prime..."); } else { out.println("The last prime discovered was " + lastprime); out.println(" at " + lastprimeModified); } } public void destroy() { searcher.stop(); } }
Break lines around brackets:
:%s/[{}]/\r&\r/g
Break lines after semicolons:
:%s/;/&\r/g
Remove empty lines:
:g/^\s*$/d
Indent:
:set ft=java
gg=G
After this, you need to tweak the code just a little to split comments.
import java.io.;
import java.util.;
import javax.servlet.;
import javax.servlet.http.;
public class PrimeSearcher extends HttpServlet implements Runnable
{
long lastprime = 0;
// last prime found Date lastprimeModified = new Date();
// when it was found Thread searcher;
// background search thread public void init(ServletConfig config) throws ServletException
{
super.init(config);
// always! searcher = new Thread(this);
searcher.setPriority(Thread.MIN_PRIORITY);
// be a good citizen searcher.start();
}
public void run()
{
// QTTTBBBMMMTTTOOO long candidate = 1000000000000001L;
// one quadrillion and one // Begin loop searching for primes while (true)
{
// search forever if (isPrime(candidate))
{
lastprime = candidate;
// new prime lastprimeModified = new Date();
// new "prime time"
}
candidate += 2;
// evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try
{
searcher.sleep(200);
}
catch (InterruptedException ignored)
{
}
}
}
private static boolean isPrime(long candidate)
{
// Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate);
for (long i = 3;
i <= sqrt;
i += 2)
{
if (candidate % i == 0) return false;
// found a factor
}
// Wasn't evenly divisible, so it's prime return true;
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (lastprime == 0)
{
out.println("Still searching for first prime...");
}
else
{
out.println("The last prime discovered was " + lastprime);
out.println(" at " + lastprimeModified);
}
}
public void destroy()
{
searcher.stop();
}
}
You could at least start by replacing all ; with a ; + line-break:
:%s/;/;\n\r/g
Then you could replace all { with { + line-break:
:%s/{/{\n\r/g
Then replace all } with } + line-break:
:%s/}/}\n\r/g
This will get you started. You'd still have to clean up all the indentation. Too bad there isn't ReSharper for Java (that I know of anyway).
Use:
http://www.prettyprinter.de/
import java.io.;
import java.util.;
import javax.servlet.;
import javax.servlet.http.;
public class PrimeSearcher extends HttpServlet implements Runnable {
long lastprime = 0;
// last prime found Date lastprimeModified = new Date();
// when it was found Thread searcher;
// background search thread public void init(ServletConfig config) throws ServletException {
super.init(config);
// always! searcher = new Thread(this);
searcher.setPriority(Thread.MIN_PRIORITY);
// be a good citizen searcher.start();
}
public void run() {
// QTTTBBBMMMTTTOOO long candidate = 1000000000000001L;
// one quadrillion and one // Begin loop searching for primes while (true) {
// search forever if (isPrime(candidate)) {
lastprime = candidate;
// new prime lastprimeModified = new Date();
// new "prime time"
}
candidate += 2;
// evens aren't prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try {
searcher.sleep(200);
}
catch (InterruptedException ignored) {
}
}
}
private static boolean isPrime(long candidate) {
// Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate);
for (long i = 3;
i <
= sqrt;
i += 2) {
if (candidate % i == 0) return false;
// found a factor
}
// Wasn't evenly divisible, so it's prime return true;
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
if (lastprime == 0) {
out.println("Still searching for first prime...");
}
else {
out.println("The last prime discovered was " + lastprime);
out.println(" at " + lastprimeModified);
}
}
public void destroy() {
searcher.stop();
}
}
Tweak the settings to get it looking how you want.
Probably you best proceed as following:
Add line breaks after characters like ;, { and }:
:s/[;{}]/\0\r/g
Go through the code and fix bad line breaks. For example comment lines started with // don't usually end in some special character and will need manual splitting
Fix the indentation with =. Use it with some movement command like =G or select the code in visual mode and then hit = to indent it.