print alternate char using two threads
Hello
I am new to threads. I have a problem with my program that should display A and B in alternate way using two threads. The output should be:
ABABABABAB
BUT,
I got different output in each run. ABAABBABA..... OR ABABBABB.....
This is my complete code:
Code:
package altPackage;
class A implements Runnable{
Thread aThread;
public A()
{
aThread = new Thread(this,"A thread");
aThread.start();
}
public void run()
{
for(int i=0; i<5 ; i++)
{
System.out.print("A");
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("A thread interrupted.");
}
}
}
}
class B implements Runnable{
Thread bThread;
B()
{
bThread = new Thread(this,"B thread");
bThread.start();
}
public void run()
{
for(int i=0; i<5 ; i++)
{
System.out.print("B");
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("B thread interrupted.");
}
}
}
}
public class altTest {
public static void main(String[] args) {
new A();
new B();
}
}
Thanks a lot in advance
Re: print alternate char using two threads
class node
{boolean isodd=true;
synchronized void prinodd()
{if(!isodd)
{try{wait();
}catch(InterruptedException e)
{System.out.print("exception caught");
}
}
isodd=false;
System.out.print("A");
notify();
}
synchronized void prineven()
{if(isodd)
{try{wait();
}catch(InterruptedException e)
{System.out.print("exception caught");
}
}
isodd=true;
System.out.print("B");
notify();
}
}
class odd implements Runnable
{node n1;
Thread t;
odd(node n1)
{this.n1=n1;
t=new Thread(this);
t.start();
}
public void run()
{while(true)
{try{t.sleep(100);} catch(Exception e){;}
n1.prinodd();
}
}
}
class even implements Runnable
{node n1;
Thread t;
even(node n1)
{this.n1=n1;
t=new Thread(this);
t.start();
}
public void run()
{while(true)
{n1.prineven();
}
}
}
class alt
{public static void main(String args[])
{System.out.println("press control +c to exit");
node n=new node();
odd a=new odd(n);
even b=new even(n);
try{a.t.join();
b.t.join();
}catch(InterruptedException e)
{System.out.println("exception caught");}
}
}
result
D:\>javac alt.java
D:\>java alt
press control +c to exit
ABABABABABABABABABABABABABABABABABABABABABABABABAB ABABABABABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABABABABABABABAB ABABABABABABABABABABABABABABAB
ABABABABABABABABABABAB
D:\>
Re: print alternate char using two threads
ankitb1989, you have been given two links in the thread you started. Kindly go through those links and edit your post accordingly.
If you continue to ignore responses and continue to post unformatted code, you may be banned for a period.
db