• Post Reply Bookmark Topic Watch Topic
  • New Topic

create-two-threads-both-display-numbers-one-after-one  RSS feed

 
Bhanjan Gouda
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Write a thread that counts 1 to 10 and another thread that counts 1 to 10, one after another.

For eg: Thread1 Output: 1 Thread2 Output:1 Thread1 Output:2 Thread2 Output:2

I have written below code

Got the output as:-

But the output isn't in sequence I want output as:
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bhanjan Gouda wrote:
But the output isn't in sequence I want output as:
Thread1 Output:1
Thread2 Output:1
Thread1 Output:2
Thread2 Output:2


There is nothing in your code that does this. You need to have those two threads communicate with each other, perhaps keep track of whose turn it is to print, and then, take turns printing.

Henry
 
Bhanjan Gouda
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry,

I am new to the Thread concept of java.Could you please tell me how two threads can communicate to each other or how can I keep track of of each thread?

Thanks,
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, the Oracle tutorials on threading may be one place to start...

https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html


Your two threads will need to share a variable, so that they know whose turn it is to print. Take a look at the synchronization section for how to protect that variable from race conditions. Your two threads will need to send notifications to each other -- so that they don't have to guess when the other thread is ready with sleep() calls. Take a look at wait/notify for that.

Additionally, the threading library contains lots of other options that may help. It can't hurt to learn those too.

Henry
 
Vibhor Rawat
Greenhorn
Posts: 9
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization should help you here.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vibhor Rawat: welcome to the Ranch
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it could take more than synchronization.  This task requires that Each thread do something and then wait for the other thread to do something.
Synchronization means that two threads can't enter a block of code at the same time.  That wouldn't keep one thread from repeatedly entering a block of code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!