How to call methods from within run()

Seems like this must be a common question, but I cannot for the life of me, find the appropriate topic. So apologies ahead of time if this is a repeat.
I have code like the following:
public class MainClass implements Runnable {
public static void main(String args[]) {
Thread t = new Thread(new MainClass());
t.start();
public void run() {
if (condition)
doSomethingIntensive();
else
doSomethingElseIntensive();
System.out.println("I want this to print ONLY AFTER the method call finishes, but I'm printed before either 'Intensive' method call completes.");
private void doSomethingIntensive() {
System.out.println("I'm never printed because run() ends before execution gets here.");
return;
private void doSomethingElseIntensive() {
System.out.println("I'm never printed because run() ends before execution gets here.");
return;
}Question: how do you call methods from within run() and still have it be sequential execution? It seems that a method call within run() creates a new thread just for the method. BUT, this isn't true, because the Thread.currentThread().getName() names are the same instead run() and the "intensive" methods. So, it's not like I can pause one until the method completes because they're the same thread! (I've tried this.)
So, moral of the story, is there no breaking down a thread's execution into methods? Does all your thread code have to be within the run() method, even if it's 1000 lines? Seems like this wouldn't be the case, but can't get it to work otherwise.
Thanks all!!!

I (think I) understand the basics.. what I'm confused
about is whether the methods are synced on the class
type or a class instance?The short answer is; the instance for non-static methods, and the class for static methods, although it would be more accurate to say against the instance of the Class for static methods.
The locking associated with the "sychronized" keyword is all based around an entity called a "monitor". Whenever a thread wants to enter a synchronized method or block, if it doesn't already "own" the monitor, it will try to take it. If the monitor is owned by another thread, then the current thread will block until the other thread releases the monitor. Once the synchronized block is complete, the monitor is released by the thread that owns it.
So your question boils down to; where does this monitor come from? Every instance of every Object has a monitor associated with it, and any synchronized method or synchonized block is going to take the monitor associated with the instance. The following:
  synchronized void myMethod() {...is equivalent to:
  void myMethod() {
    synchronized(this) {
  ...Keep in mind, though, that every Class has an instance too. You can call "this.getClass()" to get that instance, or you can get the instance for a specific class, say String, with "String.class". Whenever you declare a static method as synchronized, or put a synchronized block inside a static method, the monitor taken will be the one associated with the instance of the class in which the method was declared. In other words this:
  public class Foo {
    synchronized static void myMethod() {...is equivalent to:
  public class Foo{
    static void myMethod() {
      synchronized(Foo.class) {...The problem here is that the instance of the Foo class is being locked. If we declare a subclass of Foo, and then declare a synchronized static method in the subclass, it will lock on the subclass and not on Foo. This is OK, but you have to be aware of it. If you try to declare a static resource of some sort inside Foo, it's best to make it private instead of protected, because subclasses can't really lock on the parent class (well, at least, not without doing something ugly like "synchronized(Foo.class)", which isn't terribly maintainable).
Doing something like "synchronized(this.getClass())" is a really bad idea. Each subclass is going to take a different monitor, so you can have as many threads in your synchronized block as you have subclasses, and I can't think of a time I'd want that.
There's also another, equivalent aproach you can take, if this makes more sense to you:
  static final Object lock = new Object();
  void myMethod() {
    synchronized(lock) {
      // Stuff in here is synchronized against the lock's monitor
  }This will take the monitor of the instance referenced by "lock". Since lock is a static variable, only one thread at a time will be able to get into myMethod(), even if the threads are calling into different instances.

Similar Messages

  • How to call Method from wdDoModifyView()

    Hi,
       I have a private method and i wanna call this method from wdDoModifyView() hook method.
    but when i call mthod it gives me error the method dim() from the type ..view is not static.
    can any one tell me how can i access this method?
    best regards
    Yasir Noman

    Hi Yasir,
    i'm not sure what you mean with the "dim()" method. I guess this is the non-static method you want to call from wdDoModifyView()? You should already get a compile-time error, not only a runtime error.
    The reason is simple: There is <b>no</b> possibility to call non-static methods from a static context. Static methods "belong to" a class while non-static methods "belong to" instances of a class.
    A simple alternative is to declare dim() as public using the "Methods" tab of the corresponding view controller and use the "wdThis" reference you are getting as a parameter of the wdDoModifyView() method such as you can call wdThis.dim().
    It's <b>not</b> sufficient just to change the method to public inside the //@others section, since wdThis will not know the method then since it's not part of the controller metadata.
    Hope that helps.
    Regards
    Stefan

  • How to call methods from string names?

    On my java project i have a front controller. All the requests will first go to controller and i will make parameter validation on the controller level. If validation is completely ok, page will be dispatched to real servlet with validated parameters.
    If the request pattern is "photos" for example i will call static function and send referance of request object Validation.Photos(request); or if the pattern is "albums" function will be Validation.Albums(request).
    everything is ready on my codes except how to call a Validation function with a string name. Need a clear and a fast way because on every request i will do this.
    Thank you

    ahh life is problem;) another one i couldnt understand.
    import javax.servlet.http.HttpServletRequest;
    interface Validasyon {
            boolean invoke(HttpServletRequest request,String param);
         class IntIsNumeric implements Validasyon {
           public boolean invoke(HttpServletRequest request,String param) {
                param=request.getParameter(param);
                System.out.println("param="+param);
                try
                     Integer.parseInt(param);
                catch(NumberFormatException e)
                     return false;
                catch(NullPointerException e)
                     return false;
                int gelen1=Integer.parseInt(param);
                if(gelen1<1 || gelen1>Integer.MAX_VALUE)
                     return false;
                return true;
         }i am sending parameter to IntIsNumeric classes's invoke method like below
    Validasyon c=new IntIsNumeric();
    boolean a=c.invoke(request,"photo_id");but IntIsNumeric method does not recognize my input parameters "request" and "param" always return null. Why?

  • How to call method from  IF_SALV_WD_TABLE_SETTINGS in Wendynpro ABAP? Help!

    Hi Experts,
           I have Webdynpro for ABAP application that shows a ALV table using SALV_WD_TABLE.
    In the help doc I got the following snippet:
    "To define the selection type, use the methods of the interface class IF_SALV_WD_TABLE_SETTINGS (implementing class CL_SALV_WD_CONFIG_TABLE)."
    Selection Type Methods
    Set selection type
    SET_SELECTION_MODE
    Get selection type
    GET_SELECTION_MODE
    Can somebody tell me how to implement the above?
    I mean how to code the above so that I can make a call to the method SET_SELECTION_MODE?
    In other words how to use the above interface?
    Please provide some code snippet.
    Note that: I am using webdynpro for ABAP.
    Thanks
    Gopal
    Message was edited by: gopalkrishna baliga

    Hi GopalKrishna,
    In the WDDOINIT method of your view, use the following code:
    data: l_ref_cmp_usage type ref to if_wd_component_usage.
    l_ref_cmp_usage =   wd_This->wd_CpUse_Alv( ).
    if l_ref_cmp_usage->has_active_component( ) is initial.
      l_ref_cmp_usage->create_component( ).
    endif.
    DATA: l_ref_INTERFACECONTROLLER TYPE REF TO IWCI_SALV_WD_TABLE .
    l_ref_INTERFACECONTROLLER =   wd_This->wd_CpIfc_Alv( ).
      data:
        l_VALUE type ref to Cl_Salv_Wd_Config_Table.
      l_VALUE = l_ref_INTERFACECONTROLLER->Get_Model( ).
    l_value->if_salv_wd_table_settings~set_visible_row_count( '-1' ).
    Here I have used set_visible_row_count, you could use which ever method you desire.
    Hint: Use code wizard(Ctrl+F7)To understand better read the ALV tutorial:
    /people/sap.user72/blog/2006/01/09/wda--user-defined-functions-in-alv
    Regards,
    Srini.
    Regards,
    Srini.

  • How to call methods from .mxml file from actionscript file

    I have a Example.as and a Test.mxml.
    In this Test.mxml, I have a function which is something like:
    public function doTest():void
         Alert.show("testing!");
    How do I from example.as call this function doTest() from Test.mxml?
    I tried declaring public var test:Test inside my Example.as but I'm still unable to call that function out.
    Any idea how?

    Hi Bryant,
    You need to create an instance of the component and then attach it to the display list then only you can access the Controls with in your component other wise the controls and components are not created or initialized that's why you are thrown the null object reference error.
    So you need to do somethink like below:
    var myTestObj:Test = new Test();
    this.addChild(myTestObj); //Adds the component to DisplayList(You need to add this line of code in order to avoid the error)
    myTestObj.doTest();
    If you add your component in mxml then the component will be automatically added to the display list and you dont need to add explicitly to the display list.
    <comp:Test id="myTestObj" />
    And now if in your actionscript you call myTestObj.doTest(); no error occurs and you can see the Alert message.
    Thanks,
    Bhasker

  • How to call a set method from within a constructor

    Hello,
    I want to be able to call a set method from within a Scanner, to be used as the argument to pass to the Scanner (from a source file). Here's what i tried:
    private void openFiles()
            input = new Scanner( setSource );              
        and here is the set method:
    public String setSource( String in )
            source = in;
            return source;
        }obviously there will be more code in this method but i'm trying to tackle one problem at a time. Thanks in advance..

    The "String in" declaration says: "Nobody may ever invoke setSource() without specifying a certain String. The content of the String is known at run-time only."
    In no place in your code you say the compiler: "I want the 'in' variable (actually, parameter) of method setSource() to contain the first arg which is passed to the application".
    This is exactly the same mechanism allowing you to write "new Scanner" with something inside the two parentheses.

  • Is it possible to call methods from another class from within an abstract c

    Is it possible to call methods from another class from within an abstract class ?

    I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
    If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
    Notice that one should refine the abstract table model and you may want to create a method for something like
    public Object getValuesAtRow(int row) { return data[row;}
    to give the desired row and leave the method for
    getValuesAt alone for getting valued of particaular row and column.
    So Once you got the seelcted row index, idxSelctd, from your table
    you can get the row or set the row in your table model
    public TableExample3() {
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    // Take the dummy data from SwingSet.
    final String[] names = {"First Name", "Last Name", "Favorite Color",
    "Favorite Number", "Vegetarian"};
    final Object[][] data = {
         {"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
         {"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
         {"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
         {"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
         {"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
         {"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
         {"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
         {"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
         {"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
         {"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
         {"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
         {"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
         {"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
         {"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
         {"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
         {"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
         {"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
         {"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
         {"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
         {"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
         {"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
    // Create a model of the data.
    TableModel dataModel = new AbstractTableModel() {
    // These methods always need to be implemented.
    public int getColumnCount() { return names.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {return data[row][col];}
    // The default implementations of these methods in
    // AbstractTableModel would work, but we can refine them.
    public String getColumnName(int column) {return names[column];}
    public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {return (col==4);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    };

  • How to configure Outlook 2013 to call direct from within the application without using Lync 2013?

    I have Outlook 2013 running on Windows 7 Pro 64-Bit with Lync 2013 (Office 365 Pro). We are using a 3rd party TAPI app from FortiVoice. WE would like to be able to place calls directly from
    within Outlook either by selecting a telephone number within an email and/or via the PEOPLE (Contacts) area.
    What guidelines should we use to enable this feature and not have Lync 2013 intercepting the process i.e. let OUTLOOK handle placing calls?
    Thanks in advance for any feedback provided.

    Hi,
    There seems no solution for this issue so far.
    Here is a fix for older versions of Outlook, maybe worth a try.
    http://support.microsoft.com/kb/959625/en-us
    However, if it doesn’t work, please try Malte’s reply as the workaround in the following thread. See:
    http://social.technet.microsoft.com/Forums/office/en-US/3946f1bb-cc3d-41b6-ab9c-092d62d024d1/outlook-2013-tapi-calling-with-lync-installed?forum=officesetupdeploy
    Thanks.
    Steve Fan
    TechNet Community Support
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How to Call Methods in Ecatt?

    Hello Gurus,
    I dont find CALLMETHOD or CALLSTATIC commands in Ecatt. I am using R/3 4.7 version of SAP.
    My question also is how to call methods. I have a scenario where my test script execution depends on the return type of method. Say if the return type of method is A only then I should run the script else the script should not be executed.
    Your help in this regard is highly appreciated.
    Regards,
    GS.

    >
    Get Started wrote:
    > Hello Gurus,
    >
    > I dont find CALLMETHOD or CALLSTATIC commands in Ecatt. I am using R/3 4.7 version of SAP.
    >
    > My question also is how to call methods. I have a scenario where my test script execution depends on the return type of method. Say if the return type of method is A only then I should run the script else the script should not be executed.
    >
    > Your help in this regard is highly appreciated.
    >
    > Regards,
    > GS.
    Hi GS,
    Please use the command "CallMethod" and it is available with latest SAP version.
    You have to provide the Object Instance Parameter and Instance Method.
    Regards,
    SSN.

  • Calling methods from the Business Object BUS2032

    Hi all,
    Is it possible to call methods from the Business Object BUS2032.
    If so, how can it be done??
    Regards,

    Hi Marv,
    you sure can. Here is an extract from the SAP Help. I found it at http://help.sap.com/saphelp_46c/helpdata/en/c5/e4ad71453d11d189430000e829fbbd/frameset.htm
    <b>Programmed Method Call</b>
    Call (fictitious) method Print of object type VBAK (sales document). The method receives the parameters Paperformat and Printertype as input.
    * Call method Print of object type VBAK
    * Data declarations
    DATA: VBAK_REF TYPE SWC_OBJECT.
    SWC_CONTAINER CONTAINER.
    * Create object reference to sales document
    SWC_CREATE_OBJECT VBAK_REF 'VBAK' <KeySalesDoc>
    * Fill input parameters
    SWC_CREATE_CONTAINER CONTAINER.
    SWC_SET_ELEMENT CONTAINER 'Paperformat' 'A4'.
    SWC_SET_ELEMENT CONTAINER 'Printertype' 'Lineprinter'.
    * Call Print method
    SWC_CALL_METHOD VBAK_REF 'Print' CONTAINER.
    * Error handling
    IF SY-SUBRC NE 0.
    ENDIF.
    Cheers
    Graham

  • Calling Methods from Business Object BUS2032

    Hi all,
              Is it possible to call methods from the Business Object BUS2032.
       If so, how can it be done?? 
    Regards,

    Hi Marv,
    you sure can. Here is an extract from the SAP Help. I found it at http://help.sap.com/saphelp_46c/helpdata/en/c5/e4ad71453d11d189430000e829fbbd/frameset.htm
    <b>Programmed Method Call</b>
    Call (fictitious) method Print of object type VBAK (sales document). The method receives the parameters Paperformat and Printertype as input.
    * Call method Print of object type VBAK
    * Data declarations
    DATA: VBAK_REF TYPE SWC_OBJECT.
    SWC_CONTAINER CONTAINER.
    * Create object reference to sales document
    SWC_CREATE_OBJECT VBAK_REF 'VBAK' <KeySalesDoc>
    * Fill input parameters
    SWC_CREATE_CONTAINER CONTAINER.
    SWC_SET_ELEMENT CONTAINER 'Paperformat' 'A4'.
    SWC_SET_ELEMENT CONTAINER 'Printertype' 'Lineprinter'.
    * Call Print method
    SWC_CALL_METHOD VBAK_REF 'Print' CONTAINER.
    * Error handling
    IF SY-SUBRC NE 0.
    ENDIF.
    Cheers
    Graham

  • No access to method from within the same class

    Hey there.
    First I have to excuse my English for I'm german and just learning...
    Ok, my problem is as follows. I have a class called JDBC_Wrapper it includes the method sendQuery(String query). When I call this method from within another class (where 'wrapper' is my instance of JDBC_Wrapper) it works fine. For example:
    wrapper.sendQuery("SELECT * FROM myDataBase");
    But then I have written a method called getNumRows() into my JDBC_Wrapper class.
    This method should send a query through sendQuery(Strin query) but when calling getNumRows() it says: "java.sql.SQLException: [FileMaker][ODBC FileMaker Pro driver][FileMaker Pro]Unbekannter Fehler." (Unbekannter Fehler -> Unknown Exception). What could that be?
    I'm using jdk2 sdk 1.4.2 with BlueJ. My database is Filemaker Pro 6. The ODBC/JDBC connector works fine.
    BerndZack

    This is within my JDBC_Wrapper class:
    public ResultSet sendQuery(String query)
            if(connected)
                try
                    Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                    ResultSet rs = s.executeQuery(query);
                    return rs;
                catch(Exception e)
                    System.out.println(e);
            else
                //System.out.println("There is no connection to the datasource!");
            return null;
    public int getNumRows()
            try
                ResultSet r;
                r = this.sendQuery("SELECT COUNT(*) FROM " + table_name); // At this line the error occurs
                r.next();
                return (int)r.getInt(1);
            catch(Exception e)
                System.out.println(e.getMessage());
                return -1;
    }When I call sendQuery() from within another class it works, but calling getNumRows()
    throws an exception.

  • Calling methods from inside a tag using jsp 2.0

    My searching has led me to believe that you cannot call methods from in the jsp 2.0 tags. Is this correct? Here is what I am trying to do.
    I have an object that keeps track of various ui information (i.e. tab order, whether or not to stripe the current row and stuff like that). I am trying out the new (to me) jsp tag libraries like so:
    jsp page:
    <jsp:useBean id="rowState" class="com.mypackage.beans.RowState" />
    <ivrow:string rowState="${rowState}" />my string tag:
    <%@ attribute type="com.mypackage.beans.RowState" name="rowState" required="true" %>
    <c:choose>
         <c:when test="${rowState.stripeToggle}">
              <tr class="ivstripe">
         </c:when>
         <c:otherwise>
              <tr>
         </c:otherwise>
    </c:choose>I can access the getter method jst fine. It tells me wether or not to have a white row or a gray row. Now I want to toggle the state of my object but I get the following errors when I try this ${rowState.toggle()}:
    org.apache.jasper.JasperException: /WEB-INF/tags/ivrow/string.tag(81,2) The function toggle must be used with a prefix when a default namespace is not specified
    Question 1:
    Searching on this I found some sites that seemed to say you can't call methods inside tag files...is this true?...how should I do this then? I tried pulling the object out of the pageContext like this:
    <%@ page import="com.xactsites.iv.beans.*" %>
    <%
    RowState rowState = (RowState)pageContext.getAttribute("rowState");
    %>I get the following error for this:
    Generated servlet error:
    RowState cannot be resolved to a type
    Question 2:
    How come java can't find RowState. I seem to recall in my searching reading that page directives aren't allowed in tag files...is this true? How do I import files then?
    I realized that these are probably newbie questions so please be kind, I am new to this and still learning. Any responses are welcome...including links to good resources for learning more.

    You are correct in that JSTL can only call getter/setter methods, and can call methods outside of those. In particular no methods with parameters.
    You could do a couple of things though some of them might be against the "rules"
    1 - Whenever you call isStripeToggle() you could "toggle" it as a side effect. Not really a "clean" solution, but if documented that you call it only once for each iteration would work quite nicely I think.
    2 - Write the "toggle" method following the getter/setter pattern so that you could invoke it from JSTL.
    ie public String getToggle(){
        toggle = !toggle;
        return "";
      }Again its a bit of a hack, but you wouldn't be reusing the isStriptToggle() method in this way
    The way I normally approach this is using a counter for the loop I am in.
    Mostly when you are iterating on a JSP page you are using a <c:forEach> tag or similar which has a varStatus attribute.
    <table>
    <c:forEach var="row" items="${listOfThings}" varStatus="status">
      <tr class="${status.index % 2 == 0 ? 'evenRow' : 'oddRow'}">
        <td>${status.index}></td>
        <td>${row.name}</td>
      </tr>
    </c:forEach>

  • How to call methode on remot computer

    I have 2 Applcations on 2 computers in Network
    App 1 on PC1 send xml file to App2 on PC2
    how to call Methods in App2 on PC2 to read the file
    // clss A on PC1
    class A
    sendFile(){
    // clss B on PC2
    class A
    readFile(){
    how to cal method readFile from Class A on PC1

    By using Remote Method Invocation, the topic of this forum.
    See the Javadoc and the RMI tutorials.

  • Call methods from view controller to another (enhanced) view controller!

    Dear All,
    Is it possible to use/call methods from view controller to another (enhanced) view controller? Iu2019ve created a view using enhancement in standard WD component. I would like to call one method from standard view controller in the enhanced view controller.
    Is it possible to include text symbols as enhancement in standard class?
    u2026Naddy

    Hi,
    If you have just enhanced an existing view then you can call the standard methods in one of the new methods which you will create as part of enhancement.
    If you have created a totally new view using enhancement framework option ( Create as Enhancement ) then in this new view you won't be able to use existing methods in other view as a view controller is private in nature. So all the view attributes, context nodes and methods are Private to that view only.
    Regarding text elements, I guess adding a new text element is just a table entry in text table and is therefore not recorded as enhancement.( Not very sure about this, need to double check )
    Regards
    Manas Dua

Maybe you are looking for