ABOUT THREADS

Cound Sun provide some official material about Threads ? Because its such an important feature and there is little to none material on this topic in this language while in Java there are hundreds of links to choose from, here you have to go with what is available and it isnt much. There are only 3 links to external sites in the javafx HOW TO'S. They just give the basics but no solid examples of using threads in fx, I needed a client/server example in fx that doesnt hang the interface so i could take off from there. So please sun post some material about threading in fx other than just giving external links!!!

http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

Similar Messages

  • Question while Learning about Thread

    I am learning about thread.
    I ran the sample producer/consumer programe in Java Thread Tutorial in which I added two lines of printing out codes in class CubbyHole to observe the runing sequence better.
    The result made me a bit confused. I imagine that the result "Producer #1 put: 1" should be printed out right after "put 1", why it appeared after "get 1" and "Consumer #1 got: 1"?
    Codes are listed below:
    public class ProducerConsumerTest {
    public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    p1.start();
    c1.start();
    public class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Producer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    for (int i = 0; i < 10; i++) {
    cubbyhole.put(i);
    System.out.println("Producer #" + this.number
    + " put: " + i);
    try {
    sleep((int)(Math.random() * 100));
    } catch (InterruptedException e) { }
    public class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Consumer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    int value = 0;
    for (int i = 0; i < 10; i++) {
    value = cubbyhole.get();
    System.out.println("Consumer #" + this.number
    + " got: " + value);
    public class CubbyHole {
    private int contents;
    private boolean available = false;
    public synchronized int get() {
    while (available == false) {
    try {
    wait();
    } catch (InterruptedException e) { }
    available = false;
    System.out.println("get " + contents);
    notifyAll();
    return contents;
    public synchronized void put(int value) {
    while (available == true) {
    try {
    wait();
    } catch (InterruptedException e) { }
    contents = value;
    System.out.println("put " + contents);
    available = true;
    notifyAll();
    The result is as below:
    put 0
    Producer #1 put: 0
    get 0
    Consumer #1 got: 0
    put 1
    get 1
    Consumer #1 got: 1
    Producer #1 put: 1
    put 2
    get 2
    Consumer #1 got: 2
    Producer #1 put: 2
    put 3
    get 3
    Consumer #1 got: 3
    Producer #1 put: 3
    put 4
    get 4
    Consumer #1 got: 4
    Producer #1 put: 4
    put 5
    get 5
    Consumer #1 got: 5
    Producer #1 put: 5
    put 6
    get 6
    Consumer #1 got: 6
    Producer #1 put: 6
    put 7
    get 7
    Consumer #1 got: 7
    Producer #1 put: 7
    put 8
    get 8
    Consumer #1 got: 8
    Producer #1 put: 8
    put 9
    Producer #1 put: 9
    get 9
    Consumer #1 got: 9

    Hi alaska,
    The reason you got those results are because these are
    threads. The execution of the order of thread is
    always random (unless some explicit logic is applied)
    and CPU can execute any thread at any time within the
    process. So the results you got are perfectly right.
    Even the order of the output may change everytime you
    run the same program.
    -- manishI think you can change the predictability by setting the Producer's thread priority has higher than the Consumer's...

  • Looking for a good book about threads

    Hello all,
    I am looking for a good book about threads.
    I would like something which is both practical, but also provides some theoretical basis.
    I am an experienced programmer, with some, but not much, experience with concurrent design.
    I would greatly appreciate any suggestions.

    I found the "Java Threads" book by Oaks and Wong to be fantastic:
    http://www.oreilly.com/catalog/jthreads2/
    - K
    Hello all,
    I am looking for a good book about threads.
    I would like something which is both practical, but
    also provides some theoretical basis.
    I am an experienced programmer, with some, but not
    much, experience with concurrent design.
    I would greatly appreciate any suggestions.

  • Trying to learn about threads

    Hi guys,
    I'm trying to learn more about threads......i've written a small program for a better understand, but i don't understand the order of the output i'm getting:
    public class testme {
    public static void main(String[] args) {
    Theshape mover = new Theshape("go");
         mover.start();
    System.out.println ("checkpoint 1");
    System.out.println ("checkpoint 2");
         }//main
    }//class testme
    class Theshape extends Thread {
    public int count;
    public String thego;
    Theshape (String gg){
         thego= gg;
    count=0;
    }//constructor
    public void run(){
    try {
    do{
    System.out.println (thego);
    sleep(1000);
    System.out.println ("johnny");
    count=count+1;
    }while(count<8);
    } catch (InterruptedException e) {}
    }//run          
    }//class theshape
    ........the output i get is:
    checkpoint 1
    checkpoint 2
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    I would like to know why "checkpoint 1" and "checkpoint 2" is printed first, even though the call to the run method is made before the two statements. i would have thought that the two checkpoint statements would be printed last.
    Can anyone help?
    Thanks,
    Zaf

    After you've issued the 'mover.start()' call, a new thread pops into existence. The first thread (your main thread) continues to run while the second thread prepares itself to start up. On your machine, this startup takes a (little) while, so your main thread is able to print those two line just before the other thread is able to print something. That's all there is to it. If you put a 'Thread.sleep(1234)' between those two println statements in your main thread, the output would probably be a bit different. Give it a try.
    kind regards,
    Jos

  • Dumb question about Thread Safety in Servlets

    Hi all
    I wrote this Client API for sending requests and receiving responses to / from a multivalue database. The API is called by my Servlet. Now it seems my API is not thread safe because when several people open up the servlet at the same time, the API gets totally confused. When the API calls are inside a synchronized(){} it works just fine, but obviously at a big performance hit. Is that the wrong way of doing it??
    However when I was doing the ACID test locally on my machine, by opening two command prompts and excuting the same java program (with the same code in it as the servlet, but standalone) my API worked just fine. How come?
    Any insights appreciated as I am just learning about thread safety now (the hard way :-( )
    cheers
    Dejan

    Does this help
    Are you using one connection to the database shared by all instances
    of your servlet
    And is this connection create in the init method of the servlet and stored
    in the servlet context.
    Problem 4 people try and use your servlet at the same time, each servlet trys to
    create a connection to the database and then store it in the servlet context and
    this causes a problem.
    Solution create a listener to create the connection and store it in the servlet context
    when the servlet is created.
    If this is your problem it is not advisable to use only one connection to the db
    try using db pooling

  • Reading about threads. Where?

    Hi!
    I need to read up a bit about threads. I know the ideas behind them, but I need to know how to handle threads and write code for them in java. Does anyone have any tips about good tutorials or something?
    Thanks.

    Look out at
    1. Java Tutorial (http://java.sun.com/docs/books/tutorial/essential/threads/definition.html)
    (A must to begin with !! )
    2. www.javaworld.com Articles (search on "Java Thread")
    (Really nice !)
    3. http://directory.google.com/Top/Computers/Programming/Threads/Java/
    (Lots of stuffs!!)
    4. There are many books available on Java Thread. Even Core Java Programming from Sun Press has chapter in Multithreading. Dedicated book on Java Thread Programming is also available for serious programmers. :)
    Hope this helps.
    Regards,
    Rahul

  • I am not able to get email to sort correctly.... not about threading.

    No matter what I do the emails do not sort by date received, some crazy no rhyme or reason disorder!

    Then are you sure this is not about threading?
    Go to '''View-Sort By''' and tell me what 3 items have markers beside them.

  • I'm a newbie: I have a question about threads

    midp 2.0
    Java SE 5.0
    J2ME version 2.2
    Below is my code I'm stucked with..... The code here shows a midlet class
    and another class derived from Thread (NetworkThread). This NetworkThread
    gets started from the main midlet... Search my code for the term ??????? and
    there you find my trouble area... What I'm having trouble with is that at
    that point in my code a NetworkThread has been given a url to access, and
    putting network access in the main thread is a bad thing because one can
    never know how long it takes to access the server... I want this line:
    System.out.println("NETWORK COMMINUCATION DONE"); to be processed after
    NetworkThread is done requesting the url.... I'm not sure how to solve this
    code so that the midlet waits for NetworkThread to access the url... But
    while NetworkThread access the url I want the midlet to response to user
    input, I don't want it to look like the midlet has crashed......
    Any tips on how I can solve this issue will be greatly appreciated...
    By the way, if you see anything else that could have been improved in my
    code, then please tell me about it too....
    MY CODE:
    NETWORKTHREAD:
    package com.test;
    import java.io.IOException;
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    public class NetworkThread extends Thread
    private boolean networkStop;
    private boolean networkPause;
    private HttpConnection httpConnection = null;
    private InputStream inputStream;
    private String Url;
    private String netCommand = null;
    private String netArg = null;
    private LoginForm loginForm;
    public NetworkThread(String serverURL)
      Url = serverURL;
    synchronized void requestStop()
      networkStop = true;
      notify();
    synchronized void resumeGame()
      networkPause = false;
      notify();
    synchronized void setCommand(String cmd, String arg)
      System.out.println("setCommand = " + cmd);
      netCommand = cmd;
      netArg = arg;
      networkPause = false;
      notify();
    void pauseThread()
      networkPause = true;
    public void run()
      networkPause = true;
      networkStop = false;
      while (true)
       if (networkStop) {
        break;
       synchronized(this) {
        while (networkPause) {
         try {
          wait();
         catch (Exception e) {}
       synchronized(this) {
         if (netCommand != null) {
           if (netCommand.equals("LOGIN")) {
             //Here some networking processing will
             //be done
         else if (netCommand.equals("LOGOUT")) {
         netCommand = null;
       pauseThread();
    THE MIDLET:
    package com.test;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.IOException;
    import java.lang.String;
    public class Test extends MIDlet
      private Display display;
      private NetworkThread networkThread;
      private String Url;
      public Test() {
        display = Display.getDisplay(this);
      public void startApp() throws MIDletStateChangeException {
        if (networkThread == null) {
          networkThread = new NetworkThread(Url);
          networkThread.start();
      else {
         networkThread.start();
    public void destroyApp(boolean unconditional) throws
    MIDletStateChangeException {
       public void pauseApp() {
       public void commandAction(Command c, Displayable s) {
         if (c == okCommand) {
           networkThread.setCommand("LOGIN", "arg1");
           System.out.println("NETWORK COMMINUCATION DONE");
    }

    You will probably need to learn about HTTP and XML to complete this project. If you don't know Java at all then I would suggest starting with tutorials like these ones first
    http://java.sun.com/docs/books/tutorial/index.html
    Have a happy day.

  • Curiosity about Threads

    Good day to all.
    I have been working recently on streamlining an online application that displays / manages info from a db. In the application there are multiple views that can be called. A view expands a collection of elements so that sub elements can be viewed. There is no limit as to the depth of the objects. Generally though no more than 5 objects deep.
    The application has been plagued with high memory overhead and slow performance.
    When a user chooses to "collapse" an object, the object goes to it's deepest object removes it, moving upwards until it has no more sub objects in memory. The user was having to wait for this action to take place before the display would return.
    I added a Thread to handle the object collapse. now the object re displays as if it was collapsed ( a speed enhancement ). The true removal of sub objects happens in the thread.
    The interesting side effect of this is the memory footprint was reduced by about 25% after this change. A not intended but welcomed effect. I think this happened by reducing the amount of stuff happening in the main thread of the application, allowing the garbage collection to run more efficiently.
    Interested in other ideas / points of view.
    Thanks

    Interested in other ideas / points of view.Beeing a programmer requires you to think for yourself
    you know. It's hard and not everybody is cut out to do
    this kind of work!
    If you don't have it in you, quit now, that's my point
    of view.Not a little too harsh?
    Looks like he/she's done some thinking...
    Dorkey,
    I would imagine that any time you do less, you should take less memory.. It is a good observation that waste and cruddy code that takes up cycles and memory pointlessly should be avoided...
    ~David

  • 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.

  • Need help about Thread issue

    Given from scjp
    1.public static void main(String[] args) {
    2.        NameRunnable nr = new NameRunnable();
    3.        Thread t1 = new Thread(nr);              
    4.        t1.start();
    5.        t1.join();                   
    }There are some questions which i made up myself to test how i understand about the thread issue and I really need some experts to confirm about it.
    Question 1: At line 3, how many threads we have now ?
    my answer is
    there are 2 threads. the first one is main thread and the second one is t.
    I am not sure about the t thread because in the book, they indicate that after instantiating the thread,
    we just have a thread object but not a true thread.
    Question 2: At line 4, after t1.start(), which thread will be executed first.
    My answer is
    we dont know because it depends on the scheduler.
    Question 3: what t1.join() does ?
    my answer is
    blablabla.What I am thinking is t.join() joins the current thread to the end of t so that when t finishes the current thread can run again. However, which one is the current thread now. That is why I am stuck
    Please help me. I appreciate
    Edited by: newbie on Nov 25, 2010 4:46 PM
    Edited by: newbie on Nov 25, 2010 4:47 PM
    Edited by: newbie on Nov 25, 2010 4:49 PM

    newbie wrote:
    Given from scjp
    public static void main(String[] args) {
    NameRunnable nr = new NameRunnable();
    Thread t1 = new Thread(nr);              
    t1.start();
    t1.join();                   
    }There are some questions which i made up myself to test how i understand about the thread issue and I really need some experts to confirm about it.
    Question 1: At line 3, how many threads we have now ?
    my answer is
    there are 2 threads. the first one is main thread and the second one is t.
    I am not sure about the t thread because in the book, they indicate that after instantiating the thread,
    we just have a thread object but not a true thread.
    Don't use code blocks for prose. It won't autowrap and can lead to display problems if a line is too long.
    Which is line 3?
    What do you mean by "how many threads to we have?" Do you mean how many Thread objects exist, or how many threads (lower case "t") are executing.
    After you have called t1.start(), there are at least 2 threads executing--the main thread, and the one you started. I say "at least" because the JVM has some administrative threads of its own.
    Question 2: At line 4, after t1.start(), which thread will be execute first.
    My answer is
    we dont know because it depends on the scheduler.
    Correct. And don't think of one executing "first." They can take turns, or they can both execute at the same time (if you have a multicore or multi-CPU machine).
    Question 3: what t1.join() does ?
    my answer is
    blablabla.What I am thinking is t.join() joins the current thread to the end of t so that when t finishes the current thread can run again. However, which one is the current thread now. That is why I am stuck
    Please help me. I appreciateDid you read [url http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#join()]the docs for join()? They tell you exactly what it does. If you don't understand after reading, post again.

  • A question about thread programming ...

    Is it possible to modify the following program such that the output is
    ABCABCABC ...
    I tried yield, but not getting results on every run.
    The program is:
    public class Example1 {
    public static void main(String[] args) {
    MyThread t1 = new MyThread("A");
    MyThread t2 = new MyThread("B");
    MyThread t3 = new MyThread("C");
    t1.start();
    t2.start();
    t3.start();
    class MyThread extends Thread {
    private String message = "Hallo!";
    public MyThread() {}
    public MyThread(String s) {message = s;}
    public void run() {
    for (int i = 1; i <= 5; i++) {
    System.out.print(message);
    }

    Not really, no. It's possible (not using yield) to force threads to run in a particular order, but it's kind of missing the point of using threads in the first place!
    Yield is there purely to allow other threads the opportunity to run. It makes no guarantee about which thread will run next.
    If you really must, you need to use a wait() call to force the thread to block, notifyAll calls to resurrect them, and some commonly accessed resource that allows each thread in turn to determine IF it is its turn to run when it is awakened by the notifyAll call. That seems to be the closest to the spirit of what you're trying to do.
    It's a lot of work for something that you can more simply achieve by having only one thread of execution in the first place!

  • 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.

  • Help needed about thread priority

    Hello, could someone help me with the priorities in java? I got 10 levels in total(1-10), but I do need at least 20 levels for my multiple threads program.
    Thank you for your kind help in advance.

    First, let me apologize if I am incorrect, but it seems that the native Thread implementation restricts you to 10 priorities regardless.
    However, you can do just about anything you envision, but it will require some implementation on your part.
    You could implement a subclass of thread that contains your priority (which could be from 1-20). You could then maintain a ThreadManager that would store all running threads, and would accept requests to start and stop threads. The ThreadManager could make decisions about which threads to run, which to interrupt, which to sleep, etc., based on your priority value.
    This sounds like alot to swallow, but I'm sure it's doable if you understand threads.

Maybe you are looking for