Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know some basic concepts in java multithreading.But now i want to create 5 threads that should work concurrently.How can i get execution time of a thread?...Somebody please help me with the deep concepts of threads including methods and purposes.
Your question is really unclear. What do you mean by execution time of a thread? When it started vs. when it stopped (wall time) Or how long it was actually running, not including times it was on hold (i.e., CPU time)?
Take a look at Monitor cpu usage per thread in java?
BTW, Threading isn't something you can simply learn from a StackOverflow answer.
The official guide to Java explains concurrency quite well:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
The book "Java Concurrency in Practice" is even better.
Make a proxy
class Proxy implements Runnable {
final Runnable target;
Proxy(Runnable target) {
this.target = target;
}
public void run() {
long t0 = System.currentTimeMillis();
try {
target.run();
} finally {
System.out.println(Thread.currentThread() + " execution time = " + (System.currentTimeMillis() - t0));
}
}
}
and use it
new Thread(new Proxy(task)).start();
You can use the methods of
ThreadMxBean interface
you can get the instance using
ManagementFactory.getThreadMXBean();
after that you can call a method
getThreadCpuTime(Thread.currentThread().getId());
so your code will look like
ManagementFactory.getThreadMXBean.getThreadCpuTime(Thread.currentThread().getId());
for more details see Docs
Something like this code could be useful http://blog.sheidaei.com/2013/06/simple-thread-example-in-java.html.
You can use System.currentTimeMillis() instead of System.out.println() to get the execution time of the threads.
/**
* Created with IntelliJ IDEA.
* User: shahin
* Date: 6/5/13
* Time: 11:32 PM
* To change this template use File | Settings | File Templates.
*/
public class SimpleThread implements Runnable{
public SimpleThread(String simpleName) {
this.simpleName = simpleName;
System.out.println(">>> Constructor for " + getSimpleName());
}
public String getSimpleName() {
return simpleName;
}
public void setSimpleName(String simpleName) {
this.simpleName = simpleName;
}
private String simpleName;
#Override
public void run() {
System.out.println(" >> "+getSimpleName() + " started.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(" >> "+getSimpleName() + " stopped.");
}
public static void main(String args[])
{
System.out.println("Main Thread started.");
SimpleWaitNotifyThread simpleThread;
Thread thread;
for(int i=0;i<5;i++)
{
simpleThread = new SimpleWaitNotifyThread("Thread "+(i+1));
thread = new Thread(simpleThread,"Thread "+(i+1));
thread.start();
}
System.out.println("Main Thread finished.");
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I would like to create a code-competition in Java. The basic plan is:
Each competitor submits a class that implements the Function interface.
I apply the function of each submitted class on a set of pre-made inputs.
The grade of each submission is its number of correct outputs.
Now, I want to add a timeout: each class is allowed to run for at most 1 second on each input. If a class runs for more than one second, it should be stopped and graded 0 on that input.
My initial idea was to run each test in a separate thread, and stop the thread after a second. However, to stop a thread in Java, it is required to change its code. Here, the code is submitted by other people and I do not want to read all the submissions to verify that they allow interruption.
How can I implement such a competition?
Threads are not guaranteed to share resources fairly. Therefore, wall clock time in a "online judge" should be suspect, especially with the upper limit set in the second or minute range.
If you want to determine if people are using optimized solutions, perhaps you could set the limit a lot higher and add a few test cases with data sets that assured one was using a reasonable algorithm. With a ten minutes to compete, the odds of small scheduling differences is average out in ways that obliterate the need for more sophisticated CPU time measurements.
As for the Thread safety, you'd probably want to not use Threads in this case. Spawning a process would offload the online judge, prevent one contestant from possibly inspecting / interfering with another, provide an obvious means of termination (by the kill signal), and permit better bench marking of time (akin to the Unix command "time").
When something goes wrong in a threaded environment, it has the potential to destabilize the program, by using processes, extra barriers will prevent any such destabilization from impacting your online judge.
Using Junit? You could give this a try:
https://github.com/junit-team/junit4/wiki/timeout-for-tests
So One way that you could implement this would be to use two separate threads for 1 competitor. A ThreadTimer and A ThreadHelper
public class ThreadTimer extends Thread {
public ThreadTimer() {
}
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And ThreadHelper Which runs the function
public class ThreadHelper extends Thread {
Calculator c;
public ThreadHelper(Calculator c) {
this.c = c;
}
public Calculator getC() {
return c;
}
public void setC(Calculator c) {
this.c = c;
}
#Override
public void run() {
long startTime = System.nanoTime();
long plus = c.add();
long endTime = System.nanoTime();
long duration = (endTime - startTime);
long seconds = duration / 1000000000;
System.out.println("Add Time: " + seconds);
}
}
Your interface you created I am calling Calculator in my code.
This is calculating how long add takes and outputs the duration. I am sure the calculations are much more complex, but a potential answer to your question would come in the startup class:
public class Competition {
public static void main(String[] args) throws InterruptedException, Exception {
Calculator jim = new JimSmithsCalculator();
Calculator john = new JohnDoesCalculator();
ThreadHelper jimsThread = new ThreadHelper(jim);
ThreadTimer time1 = new ThreadTimer();
ThreadHelper JohnsThread = new ThreadHelper(john);
ThreadTimer time2 = new ThreadTimer();
time1.start();
jimsThread.start();
//This will run a loop ensuring both of the above threads are terminated...
checkSeconds(time1, jimsThread);//This also does the time check
//...Before moving on to these threads.
time2.start();
JohnsThread.start();
checkSeconds(time2, JohnsThread);
}
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
}
Since You can not use the stop() method anymore, you could throw an exception if ThreadTimer completes before ThreadHelper does.
This will output an exception and continue the program. You could then see that a competitors thread failed with the exception.
The main point to all of this random code and my answer to your question is this method :
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
I don't know if this would work exactly as you would want it.
I hope this at least sparks an idea.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am looking to create a pattern in Java that I am not sure how to properly accomplish... right now I have other solutions but I was wondering if there was a way to accomplish this sort of pattern
MethodArray methodarray;
public QueueSimulation(Method method){
methodarray.add(method);
}
public RunSimulation(){
methodarray.runall(); // runs all the qued methods in order
}
I have many different methods with different names that I would like to queue up.
In other words I have a class for example
Player.Moveup()
Player.Attack()
Player.FallOnGround()
World.LightsOff()
I have many different methods but I want to be able to put all these methods in an array and run them all like the pattern above.
This looks like something for which you can use a single-threaded Executor with Runnables or Callables which you create as anonymous classes.
A bit of googling led me to the Executors factory which helps create a single-threaded executor.
Here is an example:
public class MethodQueueSimulator {
Collection<Callable<Void>> methodQueue = new LinkedList<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String args[]) throws InterruptedException {
MethodQueueSimulator simulator = new MethodQueueSimulator();
simulator.QueueSimulation(new Callable<Void>() {
#Override
public Void call() throws Exception {
System.out.println("1");
return null;
}
});
// if using java 8+, you can use lambdas instead
simulator.QueueSimulation(() -> {
System.out.println("2");
return null;
});
simulator.QueueSimulation(() -> {
System.out.println("3");
return null;
});
System.out.println("Simulation starts");
simulator.RunSimulation();
System.out.println("Simulation complete");
}
public void QueueSimulation(Callable<Void> method){
methodQueue.add(method);
}
public void RunSimulation() throws InterruptedException {
executor.invokeAll(methodQueue);
// must call shutdown, else process will not exit
executor.shutdown();
}
}
Output when run:
Simulation starts
1
2
3
Simulation complete
As you can see, the events are executed in sequential order, and the call to invokeAll is blocking, which means that code execution waits for the tasks to complete before continuing, which is why "Simulation complete" is only printed at the end. Of course, this output does not prove the claim, but try it and see for yourself.
Instead of System.out.println, you would invoke your desired methods. I did not know what sort of return values your methods have, so I opted for Void as the return type of the Callables.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
As we know the JVM will stop if all non-daemon threads exit, and if a non-daemon thread doesn't exit, the JVM won't exit. However, when I run the code below, the result seems different than I expected.
public class Test{
public static void main(String[] args){
System.out.println("start");
new Thread(new Runnable() {
#Override
public void run() {
while (true){
System.out.println(LocalDateTime.now() + " - running");
}
}
}).start();
System.out.println("end");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("inter");
}
}
}
I think that what should happen is that the JVM shouldn't exit and will output running forever, but after 1 second the output stops. Why does this happen? Is my comprehension wrong or my is my Test class not suitable?
update: I have try the command ps | grep java,but no result,
And when I remove sleep(1000) running will be printed out forever,I'm using mac and java 1.8,anyone can tell me why this happens,thanks!
If I run
import java.time.LocalDateTime;
public class Test {
public static void main(String[] args) throws InterruptedException {
System.out.println("start");
new Thread(() -> {
try {
while (true) {
System.out.println(LocalDateTime.now() + " - running");
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(1000);
System.out.println("end");
}
}
I get
start
2016-01-15T08:30:58.378 - running
2016-01-15T08:30:58.889 - running
end
2016-01-15T08:30:59.389 - running
2016-01-15T08:30:59.890 - running
2016-01-15T08:31:00.391 - running
2016-01-15T08:31:00.892 - running
2016-01-15T08:31:01.392 - running
2016-01-15T08:31:01.893 - running
2016-01-15T08:31:02.394 - running
... many more
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My question is seems similar to other question in stack over flow,but I am not able to understand that when have more than one method in the class I put both the methods in synchronized block and I am trying to run the both methods is different threads but here the methods are running one after the other.
Main Class
/*
* 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.
*/
package Login.Package;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
/**
*
* #author ranjeeth.g
*/
public class TransportDataTransper {
public static void main(String[] args) {
Account a = new Account();
Thread t = new Thread(new WithDraw(a));
t.start();
Thread b = new Thread(new BalanceChecfk(a));
b.start();
// Thread t1 = new Thread(new WithDraw(a));
// t1.start();
// t.start();
// t.start();
}
}
Account Class.
public class Account {
public double withDr() {
synchronized (this) {
System.out.println("with draw check method = ");
for (int i = 0; i < 50; i++) {
System.out.println("i = " + i);
}
return 0;
}
}
public double balacheck() {
synchronized (this) {
System.out.println("Balance check method = ");
for (int i = 0; i < 50; i++) {
System.out.println("i = " + i);
}
return 0;
}
}
// public synchronized double deposit(double amount) {
// return 0;
// }
}
this is the same Account object a which is being used to lock
so only one thread can lock it at a time
To fully answer your question, you will need to include the "WithDraw" and "BalanceChecfk" classes. However, the "Account" class uses synchronized blocks based on an instance monitor, so if the WithDraw and BalanceChecfk classes use the account object being passed into them to delegate to the methods in Account, then whichever one happens to start first will complete first followed by the other - just as you observe. If you add a sleep of two seconds to the Account.withDr method before the synchronize, you will likely see BalanceChecfk being executed first followed by WithDraw.
Curiously, there are no shared resources which need protection in your Account object implementation, so technically there is no need at all for the synchronization, as currently implemented. If, however, you added
private Long penniesInMyAccount
to the Account object, then you would need to properly synchronize access to this shared resource from these methods. There are a number of ways to do this correctly and efficiently.
As a complete aside:
name your classes and methods clearly;
don't use abbreviations; and,
use proper grammar and spelling.
Hope that helps.
Remember, "Be kind to your future self." --Hansen
There is no difference, however, synchronized blocks have the flexibility to lock on different objects, as well as to synchronize a block of code (as their name implies) rather than an entire method.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have some questions about java threads:
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
2.how can I make one thread notify all other threads that run from the same class to stop?
3.does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
4.if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
1) Only if thread are daemons, application will not wait to close even if they are running.
Example: comment or not the setDaemon(true)
public class Test {
public static void main(final String[] args) {
new Launcher(parent).start();
}
public static class Launcher extends Thread {
public Launcher(final String name) {
this.setName(name);
}
#Override
public void run() {
System.err.println(getName() + is starting);
for (int i = 0; i < 10; i++) {
new Waiter(child + i).start();
}
try {
Thread.sleep(1000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.err.println(getName() + is stopping);
}
}
public static class Waiter extends Thread {
public Waiter(final String name) {
super(name);
super.setDaemon(true);
}
#Override
public void run() {
System.err.println(getName() + is starting);
try {
Thread.sleep(12000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
2) To force the stop, you can use different approach, different patterns. Sorry to not have THE solution. You can take a look at : http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html
3) Yeah, it's the goal of synchronized.
4) It depends what you do but basically, calling a method do not launch another thread, except if the methods does it.
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
A call to System.exit(1) will terminate the calling thread and all other threads. It is the most brutal way of ending a Java program, namely completely shutting down the JVM, and should rarely be used at all.
how can I make one thread notify all other threads that run from the same class to stop?
Not at all. If you have references to the other Thread objects, you can call Thread#interrupt(), but whether or not the other threads check their interrupted status or reach a place where they may throw an InterruptedException is left to them.
does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
Intuitively yes. However, when there is a wait() in this block, then the corresponding lock (that is, the object that was synchronized on) will be released and can be acquired by other threads.
if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
When a thread calls a method, then the same thread also executes this method (silently wondering how else it should be...)