Question on Thread concurrency

If two threads execute the below method increment() concurrently, how many different final values of X are there? You may assume that initially X has value 0.
void increment()
int temp = x;
temp = temp + 1;
x = temp;
}

That's enough of these questions. It's not a homework service. Locking this thread.

Similar Messages

  • Thread concurrency - spin lock question

    Hi everyone,
    I want to enforce some concurrency in my code so that only 5 threads are running at a time. This is quite easy to do, but I just want to know if it would be more efficent to have a spin lock like this:
    while( nActiveThreads >= 5 ){ }
    or have some kind of sleep method in the loop so that it's not continually spinning in the loop and only checks every 50 milliseconds.
    while( nActiveThreads > 5 ) {
    try {
    Thread.sleep(50);
    } catch (Exception e) {
    Any thoughts?
    BBB

    I recommend looking at the java.util.concurrent package, specifically at Executors and ExecutorService classes. You can choose from several different types of thread scheduler, telling them how many threads you with them to use.

  • A question in threading

    Hi everybody,
    my problem is as follow, I have two classes myClass and myGUI
    myClass code is
    public class MyClass
         public void start()
              while (true)
                   // do some stuff
         public void stop()
              System.out.println("Hello from stop method!");
    }myGUI code is
    public class MyGUI extends javax.swing.JFrame
    MyClass cl = new MyClass();
    public static void main(String[] args)
                        MyGUI inst = new MyGUI();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
    public MyGUI()
              super();
              initGUI();
    private void initGUI()
    // some GUI code
    myStartBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.start();
    myStopBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.stop();
    }as you can see, the start() method puts the program in an infinite loop, which makes me unable to call the stop() method using myStopBtn... So, I think this can be done using threads but actually I don't know how exactly am gonna do this
    So, any help will be appreciated.
    Thanks

    This has nothing to do with JSF.
    If you have a Concurrency specific question, post it in the Concurrency forum.
    http://forum.java.sun.com/forum.jspa?forumID=534
    If you have a Swing specific question, post it in the Swing forum.
    http://forum.java.sun.com/forum.jspa?forumID=57

  • Follow-up question to thread 'Sort by "total" in Answers'

    Seems I was a bit too quick in closing.
    Sorry for opening two threads on this, but I need to get this solved as I'm on a tight deadline here...
    The answer that pretty much solved my issue on sorting columns on sub-totals in Answers was:
    if you want to sort on sub-totals, follow this:
    i'm assuming that for that profitability column sub-total is sum of individual values for that segment..
    create other column in criteria tab:
    change it's fx to: sum(Profitability by Year, Sector)
    then, keep first sort order asc/desc on this column
    hide this column
    apply 2nd sort order asc/desc on normal profitability column..
    hope it resolve your issue.... I just have one more quick question:
    I can now sort according to sub-total, but how can I hide this new column from my table view? Clicking on the red 'x' button totally removes it as a filter.. The "hide" checkbox in the properties of the column simply grays the column out and shows it without any numbers.
    Thanks in advance
    - Magnus

    go to column properties (first option) > Column Format tab
    you find hide check box.. select and save.
    grays out the values in the column, which is correct and the same what we want..
    But, you should look at that in compound layout, not in edit properties of table...
    in compound layout, appears like it's hidden
    or
    achieve everything in pivot then exlude that particular column
    Edited by: Kishore Guggilla on Nov 29, 2010 7:18 PM

  • Need some design idea for a multi- thread  concurrent system

    I am totally new to this area. Hope ppl can give me some suggestion for the following project.
    The project is using socket to deal with huge concurrent data. Server will send me more than 50K (maybe more) XML strings in a short time.
    I need parse strings and save them in the data structure.
    What I have done is using ExecutorService to deal with this problem. Unfortunately, it's already too slow even I don't save data into data structure.(data structure will cause synchronization problem, and make system even worse).
    I was required to develop this software in a single machine and windows based OS.
    Should I only use single thread to do this project? or some other strategy?
    Can anybody give me some suggestion.
    Thanks so much.

    Peter. Thanks again.
    Could you help me to take a look at this code. Appreciate that.
    ThreadPool class:
    protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
       incoming = new Socket("127.0.0.1", port1);
       outcoming = new Socket("127.0.0.1", port2);
       out = new PrintWriter(outcoming.getOutputStream(), true);
       isr = new InputStreamReader(incoming.getInputStream());
       is = new BufferedReader(isr);
    while (true) {
         String str;
         str = is.readLine();
         if (str == null) {
                 cleanup();
                 closeSocket();
                 printout();
            } else {        
                             this.threadPool.submit(new WorkerRunnable(str,          
                                                             "Thread Pooled Server"));
           }WorkerRunnable class:
    public void run() {
    try {
                SAXBuilder builder = new SAXBuilder();
                InputSource is = new InputSource( );
                is.setCharacterStream(new StringReader(xmlString));
                org.jdom.Document doc = builder.build(is);
                org.jdom.Element root = doc.getRootElement();
                org.jdom.Element order = root.getChild("Changes");
                List orderList = order.getChildren("OrderChange");
                if (orderList.size() != 0) {
                               org.jdom.Element orderchange = (org.jdom.Element) orderList.get(0);
                               String price = orderchange.getAttribute("orderPrice").getValue();
                               String quantity = bookchange.getAttribute("orderQuantity").getValue();
                               String symbol = bookchange.getAttribute("orderName").getValue();
                                } catch(Exception e)
                              {}

  • Thread concurrency problem - how to know when thread is dead?

    My applet uses a thread to draw an iteration graph step by step.
    The user as the option of pressing two buttons:
    - PLAY button - iteration Points are stored in an arrayList and drawn step by step (a sleeping time follows each step) (drawIterations thread)
    - TO_END button - iteration Points are all stored in the arrayList (swingworker thread) and after all of them have been stored the graph is drawn instantly.
    I have problems in this situation:
    When executing the PLAY-button thread, if the user presses TO_END button, the remaining graph lines should draw instantly. Sometimes I get more points on the graph than I should. It seems that the PLAY thread, which I stop when TO_END buton is pressed, still remains storing new points into the arrayList concurrently to the new thread created after TO_END button was pressed .
    Any ideas?
    I'm already using synchronization.
    private volatile Thread drawIterations;
    public void playButtonClick(JToggleButton btn) {
         pointSet1 = new ArrayList<Point2D.Double>();
         if (drawIterations == null) drawIterations = new Thread(this,   "drawIterations");
         drawIterations.start();
    public void toEndButtonClick(JToggleButton btn) {
         stopThread() ;
         pointSet1 = new ArrayList<Point2D.Double>();
         computeIterationGraphPointsAndRefreshGraph();
    public synchronized void stopThread() {
         drawIterations = null;
         notify();
    private void computeIterationGraphPointsAndRefreshGraphs() {
         SwingWorker worker = new SwingWorker() {
              public Object construct() {
                   // compute all iteration points
                         //repaint graph
         worker.start();
    }Is there a way of testing if a thread is actually dead after setting the thread object to null??

    In general, a Thread keeps running until it's run
    method completes. Threads don't stop when their
    handle is set to null. Your run method should
    constantly be checking on a variable to know when to
    stop running and exit the run method. In this case,
    you could check on the drawIterations variable to see
    if it's null.<br>
    <br>Even using the following line on my run method I get the the same problem:
    <br>
    <br>while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
    <br>...
    <br>
    <br>Here's the whole method:
    <br>(actually there are 2 graphs being drawn and the second is only refreshed every 2 steps:)
    <br>
    <br>     <br>public void run() {
         <br>  Thread myThread = Thread.currentThread();
         <br>  int totalIterations = transientIterations +iterationsToDraw ;
              <br>  while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
              <br>     computeNextHalfIterationGraphPoint( );
              <br>      if (!TRANSIENT_IS_ENABLED || halfStep >= 2*transientIterations ) {// is     not in transient calculations
              <br>                       graphArea1.repaint();
              <br>                       if (halfStep%2 ==0 ) graphArea2.repaint();
              <br>                       if (halfStep < 2*totalIterations){//no need to execute the following block if at last iteration point
                   <br>                         if (lastIterationPointsFallOutsideGraphArea(toEndCPButtonActive)) break;
                        <br>          try {
                             <br>                      Thread.sleep(sleepingTimeBetweenHalfIterationRendering);
                             <br>                      if (threadInterrupted ){//if clause included to avoid stepping into a synchronized block if unnecessary
                                  <br>                        synchronized (this) {
                                       <br>                          while (threadInterrupted && myThread==drawIterations ) wait();
                                                      <br>    }
    <br>                                               }
         <br>                                   } catch (InterruptedException e) {
              <br>                                     break;
                   <br>                         }     
                        <br>               }
    <br>                            }
         <br>        stopThread();
         <br>     }
    <br>

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • A question about threads

    Hi to everybody,
    I'm learning Java and I would like to know what's the difference between extending the Thread class and implementing the Runnable interface.
    Why when I run two objects that are instances of a Runnable class they seem to
    run concurrently, while when I run two objects whose class extends Thread, the virtual machine first executes the first thread , and only when the first thread has died it executes the second (the two threads have the same priority).
    I would also apreciate some clarifying information about "time-slicing" and the use of the method Thread.yield();
    thanks

    Main factor what desides whether to extend Thread or
    Implement Runnable is do you want to extend another.Sorry to say this but: WRONG!
    The main factor in a decision like this should be your model, i.e. is the class you are modelling really a sub-class of Thread, or - more likely - is it a task that should be able to run (on a thread or otherwise)?
    If you are in fact implementing a new kind of Thread (i.e. YourClass is-a Thread), then you extend Thread, otherwise you should implement Runnable.
    Ex:- If your class need to Extend another class then
    you cant extend Thread so you have to use Runnable.This is true, of course, but it should be done for the right reasons.
    So: implement Runnable (unless you are implementing a new kind of Thread)

  • A question about thread safety and the Acrobat SDK

    Hi All,
    On page 12 of this FAQ: http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf
    It says that Use of any Acrobat product in a multithreaded way is technically impossible.
    I'm currently writing a command line application to perform some basic data gathering on a PDF file. The Application only makes use of a PDDoc object, and never calls on any other kind of object (i.e. AVDoc).
    The application itself is not multithreaded. All of the logic runs in a single thread.
    However, the application will be called (via the command line) from another application that /is/ multithreaded. I think that this might be fine, but I wasn't sure. In this case, would this count as a single thread, but spread across multiple processes? And if that is the case, would that be OK with the SDK?
    Or would having multiple invocations/calls into the Acrobat DLLs cause the same issue as a multi-threaded application?
    Unfortunately, I haven't done a lot of work with threads before. This might be a very silly question.

    The application would be called from a perl script that is used to automate several tasks. The app is a console application, written in C# w/ the Acrobat COM components, and Visual Studio 2005.
    The console application uses the Acrobat SDK to instantiate a PDDoc object, open a PDF, and get information about the document. It then returns results back to the console.
    So, the perl script just calls: "C:\pdfinfo.exe -f=myPdf.pdf" and pipes the result to a log file.
    In this case, it never creates a new instance of the Acrobat application, but it does use the SDK.
    The reason that I was concerned was that the perl script is multi-threaded. I wasn't sure if acrobat was just sensitive to multiple threads inside a single process, or if it was unable to handle multiple processes as well.
    PDL's answer suggests that I should be fine as long as a new process is started each time. This is good to hear.

  • Very Basic Question on Threads and Object Manipulation between classes

    I have a feeling this is on the virge of being a stupid question but hey, its the right forum.
    Lets assume I have a class that extends Jframe : Jframe1
    In that frame there is only one Jlabel : Jlabel1
    I want to create a thread that will affect Jlabel1
    The thread will run an endless loop that will.. for example change the color of the label to a random color and then the thread will sleep for a given time. There is no use in this program. Its only meant to help me understand
    I have looked up info and examples on threads. Unfortunately none were useful. Most examples try to illustrate the use of threads with the example of an applet digital clock. But it does not help with my problem, not to mention I dont want to delve into applets at this time.
    I know I have to make a class that extends thread. Does it have to be an inner class?
    How do I get to affect the frame's Jlabel1 from it? It says it doesn't know anything about it.

    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Jframe1 extends JFrame implements Runnable{
      Container con;
      JLabel Jlabel1;
      Random rand;
      Color c;
      public Jframe1(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        con = getContentPane();
        rand = new Random();
        Jlabel1 = new JLabel("bspus", JLabel.CENTER);
        Jlabel1.setOpaque(true);
        con.add(Jlabel1, BorderLayout.NORTH);
        setSize(300, 300);
        setVisible(true);
      public void run(){
        while (true){
          try{
            Thread.sleep(1000);
          catch (InterruptedException e){
            break;
          int n = rand.nextInt(16777216);
          c = new Color(n);
          SwingUtilities.invokeLater(new Runnable(){
            public void run(){
              Jlabel1.setBackground(c);
      public static void main(String[] args){
        Jframe1 jf = new Jframe1();
        new Thread(jf).start(); // you don't need to create a new thread
      }                         // because this Main thread is just
                                // another thread.
                                // here, only for demonstration purpose,
    }                           // we make a new separate thread.

  • Some question on thread

    i think threads are unpredictable.say, the following code. some questions on the code.
    public class Rpcraven{
         public static void main(String argv[]){
         Pmcraven pm1 = new Pmcraven("One");
         pm1.run(); // line1
         Pmcraven pm2 = new Pmcraven("Two");
         pm2.run();  // line 2
    class Pmcraven extends Thread{
    private String sTname="";
    Pmcraven(String s){
         sTname = s;
    public void run(){
         for(int i =0; i < 2 ; i++){
              try{
               sleep(1000);
              }catch(InterruptedException e){}
              yield();
              System.out.println(sTname);
    }question 1 > note line 1 and line 2 . does this two threds are staarted at the same time ? or line 1 first and line 2 second as in the code ? this is very much important to me.
    question 2 > ok, whoever goes first , now lets come to the try-catch block . there is sleep() who will sleep first ? so i need to know which thread is going to sleep first ? bcoz then i can say who will get the yield() method.
    i find difficult to predict the output of this thred.
    Output of One One Two Two.
    one more thing, threads are always called by start() method ( run() is called implicitly) . here start() is not usued . still the code is working . how ?

    question 1 > note line 1 and line 2 . does this two
    threds are staarted at the same time ? or line 1 first
    and line 2 second as in the code ? this is very much
    important to me.If it's important, you are doing something wrong...
    First, you shouldn't call the threads' run() method, that doesn't "start" the thread, it just calls run(). Use start() instead.
    The threads are sort of started in order, but probably not in the way you think.
    Think of it like this: there is a list of threads in the JVM. start() puts the thread in the list. After that, the CPU of your computer can run any thread in the list, for as long as it feels like. The CPU might run thread 1 for a few instructions, then thread 2 for a while, or it might start with thread 2, ... If you have a multi-CPU machine, the threads are run at the same time. It's unpredictable, except when you do explicit synhcronization or waiting.
    question 2 > ok, whoever goes first , now lets come to
    the try-catch block . there is sleep() who will sleep
    first ? so i need to know which thread is going to
    sleep first ?This is unpredictable. You can't know it. It will vary from run to run.
    If you need two threads to do something in a predictable order, you'll need to do synchronization and waiting.
    one more thing, threads are always called by start()
    method ( run() is called implicitly) . here start()
    is not usued . still the code is working . how ?You are not starting the threads, you are calling their run() methods sequentially.

  • A question about thread

    i am learning up on threads.
    A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
    so lets say i have 2 classes, A and HelloThread
    A
    public class A {
         public static void main(String[] args) throws IOException {
            //(lots of codes)
    }HelloThread
    public class HelloThread extends Thread {
        public void run() {
            System.out.println("Hello from a thread!");
        public static void main(String args[]) {
            (new HelloThread()).start();
    }this is what i am confused.
    both classes have public static void main(), is that possible?
    if no, then what command makes the thread run concurrently?
    (since it says many threads can run concurrently)
    i m soo confused.
    tq

    When you run a Java program the java command gives the name of the main class. The interpretter looks in the class you name for a main() method. There's nothing special about the method, appart from it being used this way. It doesn't matter if there are identical methods in other classes because you tell the interpretter which one to look in.
    By the way, it's not good practice to subclass Thread this way. To run code in a Thread, create a class (or, very often and anoymous class object) which implements Runnable and use the Runnable object in the constructor of Thread.

  • Question on Thread synchronization

    Why the use of synchronized key word doesnt guarantee sequential
    execution of the code across multiple threads , unless we use wait and
    Notify ?

    The question is non-sensical - if you want sequential execution then there absolutely no point in using multiple threads in the first place.

  • Question on Thread

    Hi All
    I got a doubt while implementing threads, so thought of getting it cleared before i do some progress. I have a method from where the new thread is getting called and in the next line i have return statement.
    Method(){
    Calling thread ();
    return statement;
    What happens here? I mean Does the parent process completes before the child process?
    Thanks
    Simi

    user11138361 wrote:
    I exactly mean the same
    int foo() {
    Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();
    return 1;
    My question was If the child process is running then how the parent process(Px) will complete ?There is no child process. You're creating a thread, not a process.
    That point aside, I don't understand your question. The current thread and the new thread are totally independent of each other. Why would you expect that one can't complete while the other is still running?
    Also note that the parent thread is NOT the same as that foo() method. The thread doesn't necessarily end when the foo() method does. It can, though, and I don't know why you'd think otherwise.
    EDIT: My guess is that what you're really confused about is, "How can method foo() end when one of its 'steps' (that is, the new thread) is still executing?" The answer is that all of its steps are done, even if the other thread is still running.
    foo()'s step of calling t.start() has finished. That doesn't mean the new thread has finished, however. The start() method says, "create a new, +independent+ thread of execution and set it running." As soon as it does that, start() is done, and now the new thread is running (or eligible to run) independently of the current thread.
    Imagine I have a list of chores: Take out trash; Wash dishes; Vacuum living room. That list is the foo() method. You are a new Thread object. After I wash the dishes, I tell you "Go to the store, and buy apples, milk, eggs, chicken, and bread." You leave to do your work, and as soon as I have told you what to do, I continue with my tasks. We do our work independently of each other, and I can finish the chores on my list without waiting for you to come back from the store.
    Edited by: jverd on Mar 21, 2011 11:27 AM

  • Question about Threads

    Hi,
    imagine that I have a class as below:
    public class MyVector
    private IntegerVector vect;
    public Synchronized void write(){
    vect.f();
    public Synchronized void read(){
    vect.g();
    Where f and g are non Synchronized and non-static public methods of IntegerVector .
    Imagine that two threads as below:
    thread one :
    class ThreadOne extends Thread
    public ThreadOne(MyVector v)
    this.v=v;
    public void run()
    v.write();
    class ThreadTwo extends Thread
    public ThreadTwo(MyVector v)
    this.v=v;
    public void run()
    v.read();
    My question is that if there will be any conflict between thread1 and thread2 for having the lock on
    object MyVector v ?the methods read and write are Synchronized but they call non-Synchronized methods f() and g()
    of field "IntegerVector vect" of "MyVector v "!
    Thanks,
    Behnaz

    bandarurm wrote:
    jverd wrote:
    bandarurm wrote:
    @OP - Also, remember that there are only two types of locks (aka monitors), which are Object level lock and Class level lock. No. All locks are identical.Could you explain this further? As I thought there is a class level lock (java.lang.Class) for a class with static synchronized methods. And, there is an object level lock, which is a built-in lock that every object has in java, by default.Whenever you synchronize a block of code or a method, you're just obtaining some object's lock. Synchronized methods are just shorthand for obtaining particular objects' locks.
    Synchronization is always the same. Declaring a method synchronized is just shorthand for what you could do by explicitly syncing a block of code on a particular object.
    class Foo {
      synchronized void bar() {
        // body
      // is the same as
      void bar() {
        synchronized (this) {
          // body
      // and
      static synchronized qux() {
        // body
      // is the same as
      static qux() {
        synchronized (Foo.class) {
          // body
    }In all cases, you're just syncing on an object, and which object doesn't matter, except to other methods or blocks that sync on the same object. Everything else is identical.
    The fact that synchronized static methods obtain one particular lock and non-static ones obtain a different one is not indicative of different kinds of locks. It's always just some object's lock, and no lock behaves differently from any other.
    Edited by: jverd on Apr 20, 2009 10:46 AM

Maybe you are looking for

  • How can I get my attachments to open in their respective applications versus in my downloads

    Everytime I open an email attachment, it automatically saves in my downloads folder. If I open a word doc or xls, I would like them to open in their proper applications. Please help. Thank you! jlm

  • Ican't send or request gifts in farmtown and it is very slow

    when I am working in Farmtown on facebook I can't send gift to friends.I was told to try micro soft browser.and I did and it worked great. except some things only work with your browser in farmtown. another game I play I have used your browser for a

  • "Apple Display Thunderbolt" as TV

    Hello guys! I wanted to use an "Apple Display Thunderbolt" as TV. I need an adapter to convert the HDMI signal from the decoder to form Thunderbolt monitor. Does anyone have any idea. just need the video signal, the audio can send to an independent s

  • Screen dims

    I have a 20" duo-core imac (white) at work and a 20" duo-core (aluminum) at home and have the same issue on both machines where the screen will dim if the computer is inactive for a brief period. Its not that the computer is going to sleep with the s

  • Adding to a string

    hi is there a function in java that lets you add a certain number of characters to a string like string.add( number of occureences, character to add) eg string = "abc" string.add(5,'d') then the string would equal "abcddddd" is there anyway to do thi