Two Loops at almost the same time - java

i don't what this process is called, but i've seen that it's possible.
what is this process called?
basically, i have a method that has a loop, and in every iteration has a delay second.
function myLoop(float delay)
{
for(int x=0; x<100; x++)
{
Print("Loop number: " + x);
TimeDelay(delay);
}
}
i'd like to run the second instance without waiting until the first instance is finished.
function main()
{
myLoop(2);
myLoop(2);
}
so once the first myLoop started, i'd like the second myLoop to start immediately, they would be both running at the same time, my question is, what do you call this process?
is this process possible?(in java for example).
Thank you very much! :)

This typically requires some form of multithreading.
You would do something like:
function main
start thread, calling myLoop(2)
start thread, calling myLoop(2)
' Potentially wait for threads to complete
end function
For details on how this works in Java, see the Concurrency Tutorial.

Java implementation of your program will be similar to this.
class MyThread implements Runnable{
Thread t;
int delay;
MyThread (int delay) {
t = new Thread(this,"My thread");
this.delay = delay;
t.start();
}
public void run() {
for(int x=0; x<100; x++)
{
Print("Loop number: " + x);
TimeDelay(delay);
}
}
}
class Demo {
public static void main (String args[]){
Thread t1 = new MyThread(2);
Thread t2 = new MyThread(2);
t1.join();
t2.join();
}
}

The answer for your questions.
What is this called?
A: Threading - running multiple tasks at a same time. (We call it as forking in PHP/Linux applications.)
Is this possible in Java?
A: Offcourse this is possible. To be frank this is more easier to implement in Java. Please follow the above answers.

This is called an asynchronous computation. You can solve this cleanly with Futures. (You don't really need to do full-blown multithreading)
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html

Related

Thread execution after .start() method

I am wondering what happens in the following scenario:
Two threads are created:
Thread t1 = new Thread();
Thread t2 = new Thread();
Assume these just print out a string, the threads then call the .start() method:
t1.start();
t2.start():
My question is why do these threads print in a seemingly random order each time? I know threads execute concurrently but would t1 not always finish before t2 due to the sequential execution of the main process?
Calling start() on a Thread doesn't necessarily result in the thread running immediately after. It is possible for other things to happen in between your calling start() and the first line of your thread's run() method actually being run. And even once your run() is actually running, it's also possible that other things happen before, during, or after your run() method finishes.
In your question, you said: "assume these just print out a string" – here's an implementation of run() which does that:
public void run() {
System.out.println("my name is: " + getName());
}
So it's possible that t1 starts to run first, but before it actually calls System.out.println, t2 is allowed to execute and runs to completion, then t1 is resumed.
If this kind of behavior won't work for your use case, you'll need to add some kind of concurrency protection to coordinate how and when your threads run.
UPDATE:
To illustrate the unpredictable sequence of thread execution, run this code a few times and observe the output:
public class Example {
public static void main(String[] args) {
for (int k = 0; k < 10; k++) {
new TestThread(k).start();
}
}
}
class TestThread extends Thread {
private final int k;
TestThread(int k) {
this.k = k;
}
#Override
public void run() {
System.out.print(k + " ");
}
}
Here is the output from one of my local runs:
7 0 1 5 4 6 3 2 8 9
Thread.start() doesn't guarantee execution. It will just make the Thread state runnable and hand over to the Thread Scheduler. It is the Thread Scheduler which decides which thread to run when.
If you need code to execute in a defined order on multiple threads, you need to add synchronization code between those threads.
Otherwise, the system is free to schedule execution in any order it sees fit.

Why this program involving thread returns "Yes" first

When I run the following code, it returns Yes followed by 9 No. But I thought it should be 10 No, because the start() will execute the run segment, which set the mysting to No, isn't it? Please help explain. Thanks!
class myThread implements Runnable{
String mystring = "Yes ";
public void run() {
this.mystring = "No ";
}
public static void main (String args[]) {
myThread t = new myThread();
new Thread(t).start();
for (int i=0; i<10; i++){
System.out.println(t.mystring);
}
}
}
Threads are used for parallel execution. This means the code of the Thread runs parallel to the one of the main-Method. But there's no guarantee about the order of execution. Which is exactly what you experience here. The code in main is slightly faster than the start-up of the Thread and thus the first output is "yes".

How to make two threads work in same time

I make two threads: one for fill an array and the second one print it. It seems like the two thread don't work in same time.
When i run the code its print first thread working then its print the array and second thread working how i can know if they working on same time or not?
here is my code:
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
firstthread f=new firstthread();
secondthread s=new secondthread();
s.start();
f.start();
}
}
and the class the contain both fill and print method:
public class Array {
private static int [] ar=new int[500];
public static void fillarray()
{
for (int i = 0; i < ar.length; i++)
ar[i]=i;
}
public static void printarray()
{
for (int i = 0; i < ar.length; i++)
System.out.print(ar[i]+" ");
}
}
the first thread class:
public class firstthread extends Thread{
public void run() {
Array.fillarray();
System.out.print("first thread working ");
}
}
the second thread class:
public class secondthread extends Thread{
public void run() {
Array.printarray();
System.out.println("second array working");
}
}
The fillarray and printarray methods are running too fast so you aren't getting threading.
Add Thread.sleep(10) to each loop. That way the code will run much slower and the threads will intersperse. They will probably alternate with this approach.
Then change in to sleep a random # of seconds and you'll see different behavior.
You want an implementation of producer-consumer problem bro... Frankly speaking, without having a lock on the Object's monitor, you dont have control over anything. You dont have control over how much time a thread executes (Timeslice provided to it). If the time slice is too long, you will feel that one thread executes after another because your processor is so fast, your first thread will get ample time to finish its work . If you want to know how threads work exactly, use wait() and notify() and synchronized methods to change it into a producer-consumer problem.
Jeanne is also right, you can put sleep() , there's a 90 percent chance that it might work.
You could increase the number of elements being filled/printed.
There's a 70% chance of you reading more than what you wrote(filled in the array) if you dont use syncronized/wait/notify.
Starting a thread takes some time to the JVM. The first thread executes its run() method faster than the other thread is started. That's why you see that behavior.
Question isn't clear. Do you mean how can you tell if they are working on the same array? If that is the case the answer is Yes. the array is static meaning there would be only one of its kind which would belong to the class array. So there wont be multiple instances of it being worked on by the different threads.
As stated above, the threads run very fast. So even though they are accessing the same object, one thread would finish its job before the second even begins

How to make threads in Java run concurrently

I'm trying out this code and I'm a bit confused/surprised at the output I'm getting. I'm still new to Java but I'm aware that threads should normally run concurrently. It seems my "printB" thread here waits for the "printA" thread before it starts executing. I've run the program several times (hoping to get a mixture of both threads' outcome i.e. something like: a, a, b, a, b, a...) but still I get the same output (i.e. "A" getting printed first, before "B"). Why is this happening and how can I alter the code to start behaving normally?
Any inputs/suggestions would be much appreciated. Thanks.
Also, I'm trying out the same code using the extends Thread method and it doesn't work.
class PrintChars implements Runnable{
private char charToPrint;
private int times;
public PrintChars(char c, int t){
charToPrint = c;
times = t;
}
public void run(){
for (int i=0; i<times; i++)
System.out.println(charToPrint);
}
public static void main(String[] args){
PrintChars charA = new PrintChars('a', 7);
PrintChars charB = new PrintChars('b', 5);
Thread printA = new Thread(charA);
Thread printB = new Thread(charB);
printA.start();
printB.start();
}
}
Extends Thread method below:
class PrintChars extends Thread {
private Char charToPrint;
private int times;
public PrintChars(char c, int t){
charToPrint = c;
times = t;
}
public void run (){
for(int i =0; i<times; i++)
System.out.println(charToPrint);
}
PrintChars printA = new PrintChars('a', 7);
PrintChars printB = new PrintChars('a', 5);
printA.start();
printB.start();
}
In multithreading, usually you can't make any assumption about the output.
Perhaps the time used to create the thread is very long, hence the previous thread has time to complete entirely, since its execution is very short.
Try with 7000 and 5000 instead of 7 and 5.
Each thread takes time to start and can run to completion very quickly. I suggest you add Thread.sleep(500); after each line printed.
try {
for(int i =0; i<times; i++) {
System.out.println(charToPrint);
Thread.sleep(500);
}
} catch(InterruptedException ie) {
}
Try running it a few more times. When I tried it with 700/500 I noticed some interweaving.
Thread scheduling is not deterministic. It's perfectly fine for the OS to schedule one thread, and only schedule the second after the first has completed.
If you think about it from the OS' point of view, it makes sense.. If somebody asked you to do two tasks, it may be more efficient to do one and then the other.
When the task takes too long to execute, as an OS you'll probably want to task switch and do something on the other task as otherwise the other task won't progress at all, and the app. that issued the task will feel discriminated.
You can see this by making your task run longer, e.g. by adding Thread.sleep statements or calculating PI or something (or just loop for more than 7, like 70000).
I think the execution times for your threads are too short to notice an effect. You can try higher values for times. I would try something >10000. Another option is to increase the execution time by making the method slower:
public void run(){
for (int i = 0; i < times; i++) {
System.out.println(charToPrint);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Your code is behaving normally only, if your expectation is to have mixture of a and b's printed, then you should sufficiently print chars not just couple of times, or use Thread.sleep() or do a busy wait running a for loop doing nothing for a million times.

How to wait for a thread to finish before starting more in Java

So say that I have 10 things to run, but I can only have 3 threads running at a time.
ArrayList<NewThread> threads = new ArrayList<NewThread>();
for(int i = 1; i < args.length; i++) {
NewThread t = new NewThread(args[i]);
threads.add(newThread);
if( (i%3) == 0) {
for (NewThread nt : threads) {
nt.join();
}
threads.clear();
}
}
The class NewThreads implements Runnable. I thought the join() method would work to make it wait for the threads to finish before looping around again and kicking off the next batch of threads, but instead I get a stack overflow exception. I think I am implementing join() incorrectly, but I am unsure how to do it. I currently am doing it as
public void join() {
this.join();
}
in my NewThread class. Any suggestions on how to get this working or a better way to go about it?
You are implementins or overriding join to call itself endlessly
public void join() {
this.join(); // call myself until I blow up.
}
The simplest solution is to use Thread.join() already there, but a better solution is to use a fixed size thread pool so you don't have to start and stop threads which can waste a lot of time and code.
You can use an ExecutorService
ExecutorService es = Executors.newFixedThreadPool(3);
for(int i=0;i<10;i++)
es.submit(new Task(i));
This is just a simple mistake.
Remove the method
public void join() {
this.join();
}
This method calls itself again and again.
NewThread should extend Thread.
Or 2nd way:
keep the method and call
Thread.currentThread.join();
The rest looks fine.

Categories

Resources