i want to create two thread one thread will print odd number and another thread will print even number. but the number should be in a sequence likehelp me.1 2 3 4 5 6 7 8 9 10
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
i want to create two thread one thread will print odd number and another thread will print even number. but the number should be in a sequence likehelp me.1 2 3 4 5 6 7 8 9 10
First of all you should create 2 threads, either pass a runnable to either of them or use annonymous sub-classes of thread that overwrite their run() method.
Have them print numbers inside a for loop.
Then think of a good way to synchronize their actions, perhaps a lock, or an atomic counter. Choice is yours.
yea i already did that .but i am stuck in the next part means synchronization of method.please help me to write that code.
actually i wrote the below code.
package com.java.demo;
public class Practice1
{
public static void main(String [] args)
{
Thread t2=new MyThread1();
t2.start();
Thread t1=new MyThread();
t1.start();
}
}
class MyThread1 extends Thread
{
public void run()
{
for(int i=1;i<=10;i+=2)
{
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread
{
public void run()
{
for(int j=2;j<=10;j+=2)
{
System.out.println(j);
try {
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
but i am getting o/p-
i want o/p as-1
2
3
4
6
5
7
8
10
9
1
2
3
4
5
6
7
8
9
10
What methods for synchronization do you know and which do you want to use?
if we write synchronized before any method it will get synchronized. but in this program what is the solution i am not getting.
I meant other ways of synchronization, there is more then one.
Maybe google "consumer producer synchronization" and read up on some documentations and articles describing what it is.