• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads making me behave like threads :-(  RSS feed

 
sujit singh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/*
Kindly help me
why is the run method in Thread1 not able to access the pop() method and the variables defined in public class MultithreadingDeme
kindly help. I think I am making a comceptual mistake. Please explain me what ?
*/

//Demonstrating various aspects of multithreading including synchronization
//creating a stack of ten elements and accessing the top most number

public class MultithreadingDemo
{
public static int controlThread;
public static int TopOfStack = -1;
public int[] Stack;
public void PutIn(int toPut)
{
if(TopOfStack >= 9)
{
System.out.println("Can't put STACK IS FULL ");
}
else
{
TopOfStack++;
Stack[TopOfStack] = toPut;
}
}
public int PopUp()
{
if(TopOfStack <= -1)
System.out.println("Stack does not has any elements");
else
{
System.out.println("The top most element is : " + Stack[TopOfStack]);
TopOfStack--;
}
return 0;
}

public static void main(String args[])
{
MultithreadingDemo exp = new MultithreadingDemo();
Thread1 First = new Thread1();
First.start();
System.out.println("Exiting main Thread");
}
}

class Thread1 extends Thread
{
public void run()
{
System.out.println("Extends thread1 created");
while(true)
{
exp.PopUp();
exp.PutIn(exp.controlThread);
exp.controlThread++;
}
System.out.println("Exiting Extends thread");
}
}
class Thread2 implements Runnable
{
public void run()
{
System.out.println("In implements thread2 and exiting");
}
}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because Thread1 is a seperate object. It has to follow all the rules that any object must follow. If you want it to access the popup method in the MultiTreadDemo Object, it needs a reference for it.
change Thread1 to

Now you will have a MultithreadingDemo object in your thread to access change the main in MultithreadingDemo to

Hope this helps
[This message has been edited by Carl Trusiak (edited January 11, 2001).]
 
paul wheaton
Trailboss
Posts: 22537
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm moving this to a threads forum
 
sujit singh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Karl . I got the point.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!