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.

Similar Messages

  • 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

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

  • Questions about thread priority...

    Situation 1) setPriority(int adsa)
    public class ThreadPrioDemo1 {
          static class Demo1 implements Runnable{
          public void run(){ //blablabla}
         public static void main(String[] asdf){
              Runnable r = new Demo1();
              Thread myThread = new Thread(r);
              Thread mainT = Thread.currentThread();
              //mainT's priority is 5, so as myThread.
            mainT.setPriority(10);
    //mainT's priority to MAX, this simultaneously changes myThread to 10 as well.
            //or
            myThread.setPriority(10);
    //myThread priority to MAX, however, this does not change mainT to 10
    }Question 1), why if main Thread is set to a certain priority, the thread it creates automatically change its priority to the same as well, but the reverse is different??
    Situation 2) this is slightly more complex
    public class ImplementingRunnable {
         public static void main(String[] args) {
         Thread mainT = Thread.currentThread();
              for(int ii=0 ; ii<args.length ; ii++) {
                   Runnable r = new MyRunnable(args[ii]);
                   Thread t = new Thread(r);
                t.setDaemon(true);
                //t.setPriority(Thread.MAX_PRIORITY);
                   t.start();
    }and
    public class MyRunnable implements Runnable {
        public void test(){
        System.out.println("test");
         String message;
         public MyRunnable(String msg) {
              message = msg;
         public void run() {
              Thread me = Thread.currentThread();
              try {
                   for(int ii=0 ; ii<10 ; ii++) {
                       //case (1) me.setPriority(Thread.MIN_PRIORITY);
                        me.sleep(3);
                        System.out.println(message);
                        //case (2) me.setPriority(Thread.MIN_PRIORITY);
              } catch (InterruptedException ie) {
    }In class ImplementingRunnable, how is the commented code line related or counter-related with the commented case 1 code line in MyRunnable??
    Please help
    thanks

    Let me speak my question again very simply:
    1)
    Say I have two threads, 1 is main() thread, the program entry point, 2 is another thread created by main().
    Now, the default priority for both two is 5. If I change the priority for main() to a certain level, the other thread created by it automatically change its priority to the same level? why? and however, the reverse (in this case, if I change the priority for the thread created by main()) is not.
    2)
    public class Demo{
    static class MyThread implements Runnable{
    public void run(){//some thing}
    Thread t = new Thread(this);
    t.setPriority(10);
    public static void main(String[] afd){
    Runnable r = new MyThread();
    Thread t1 = new Thread(r);
    t1.setPriority(1);
    }What can you say about both bold code lines?
    If I use println() to track the Priority, the final priority, that is, t1, is 1. It is logical, however, the program behaves differently without the bold code line in the static class MyThread, despite the final priority for t1, is the same, 1.
    Any help by now??
    thanks alot

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

  • 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 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!(help a chinese learner)

    package thead;
    import javax.swing.UIManager;
    import java.awt.*;
    class mythread implements Runnable {
    int i;
    String name;
    mythread(String nn){
    i=0;
    name=nn;
    public void run(){
    System.out.println("name"+"starting!");
    try{
    do{
    Thread.sleep(1000);
    System.out.println("IN"+name+"the count is"+i);
    i++;
    while(i<10);
    catch(InterruptedException wwwww){
    System.out.println("interrupt");
    class use {
    public static void main(String[] args) {
    System.out.println("starting");
    mythread pp=new mythread ("ok");
    Thread ww=new Thread(pp);
    ww.start();
    do{
    System.out.print(".");
    try{
    Thread.sleep(100);
    catch(InterruptedException wwwww){
    System.out.println("interrupt");
    while(pp.i!=10);
    System.out.println("ending");
    Why the result is :
    starting
    .okstarting!
    .......INokthe count is0
    ....INokthe count is1
    ..........INokthe count is2
    ...........INokthe count is3
    ........INokthe count is4
    ....INokthe count is5
    ....INokthe count is6
    ............INokthe count is7
    ...........INokthe count is8
    ..........INokthe count is9
    ending
    i can not really understood
    is this about my machine?

    Hmm i was trying your code on my machine and the output was:
    starting
    .namestarting!
    .........INokthe count is0
    ..........INokthe count is1
    ..........INokthe count is2
    ..........INokthe count is3
    ..........INokthe count is4
    ..........INokthe count is5
    ..........INokthe count is6
    ..........INokthe count is7
    ..........INokthe count is8
    ..........INokthe count is9
    ending
    so i guess something's wrong with your vm/os/machine.

  • 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

  • Question about Threads/Servlets

    Let's say I have a servlet that opens a socket connection to a server application. On the server end, I would have to make a thread for each connection. But what about the Servlet? do I have to deal with Threads on the servlet side or does the servlet engine takes care of that?

    Unless your servlet implements the SingleThreadModel interface, the servlet container shoud take care of running each request to your servlet in a separate thread.
    Andy Nguyen

  • Challanging question about Threads.  Can anyone help?

    Hello,
    I've been learing how to use threads and I have run into a little rut. I am making a game that listens for clicks of the mouse on the board AND allows people to talk to each other in a chat box.
    I've made a chatThread and in the public void run() method I can do the following...
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    catch (Exception h){}
    this pastes whatever the other person wrote into the public chattext area. now my problem is this. I need another thread that listens for button clicks. If the button is clicked on one side, the other side needs to be able to read that click and perform a certan task. I only have 1 thread running, but I have made an instatance of PrintWriter for the text and DataInputStream for the integer value. I have tried things like this and they really don't like me. (they cause faluts and whatnot)
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    ServerIn2a.readInt();
    catch (Exception h){}
    Sometimes the integer will read into the ServerIn2a and then when i try to chat it can't read into the ServerIn varialble.
    Do I need to make two seperate thread and somehow pause one and run one, then pause the other?
    Thanks for your help!

    Ok, sorry, here is a better description of what my program looks like (the parts that concern this topic)...
    public class Game extends JApplet implements ActionListener, Runnable{
    PrintWriter ClientOut = null; // to send messages to the server
    BufferedReader ClientIn = null; // to receive messages from the server.
    PrintWriter ServerOut = null; // to send messages to the client
    BufferedReader ServerIn = null; // to receive messages from the client.
    DataInputStream ClientIn2a = null; // to send messages to the server
    DataOutputStream ClientOut2a = null; // to receive messages from the server.
    DataInputStream ServerIn2a = null; // to send messages to the client
    DataOutputStream ServerOut2a = null; // to receive messages from the client.
    //On the main screen, if they press the "host" button they become the host and the this happens.....
    //I want these two lines to read text from a dialog box and then pass that text to the other person      //playerinput from a dialog box so it can be passed
    ServerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ServerOut = new PrintWriter(clientSocket.getOutputStream(),true);
    //When they click on a button, I am trying to read the buttons coordinate which will be a Integer value. I //I want to get that integer value to the other person so I make these DataInput and Output variables.
    ServerIn2a = new DataInputStream(clientSocket.getInputStream());
    ServerOut2a = new DataOutputStream(clientSocket.getOutputStream());
    //now I made a thread that is always supposed to listen to perform the action of sending the text to
    //the appropriate text listener and to send the integer to the appropriate DATAINPUT listener.
    Thread ServerThread = new Thread(this)
    ServerThread.start();
    //on the main screen, if they press the client button......
    ClientIn = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
    ClientOut = new PrintWriter(serverSocket.getOutputStream(),true);
    ClientIn2a = new DataInputStream(serverSocket.getInputStream());
    ClientOut2a = new DataOutputStream(serverSocket.getOutputStream());
    //now I made a thread that is always supposed to listen and perform the action to send the data to the
    //other person
    Thread clientThread = new Thread(this);
    clientThread.start( );
    //here is the actionPerformed method. They press enter in the text area box and this gets run.....
    if(player==1){
    //THE TEXT THEY TYPE FIRST GETS PASTED INTO THEIR OWN CHAT AREA
         chatText.append(HostUserName+": " + messageField.getText() + "\n");
         //NOW I WANT TO SEND WHEY THEY TYPE TO THE OTHER PERSON
    try{
    ServerOut.write(HostUserName+": " + messageField.getText()+"\n");
    ServerOut.flush(); }
    catch(Exception e){Mbox.showMessageDialog(null,"Chatting error","connect",1);}
    //here is my run method (this is where I think I am having my problems and that I need help with.
    public void run(){
         if(player == server){
         while(true){
         try{
         //THIS IS WHERE THE INTEGER SHOULD BE READ INTO
                   performAFucntion(ServerIn2a.readInt());}
              catch(Exception h){}
              //THIS TRY STATEMENT IS WHERE THE TEXT SHOULD BE READ
         try{   
              chatText.append(ServerIn.readLine()+"\n"); }
         catch (Exception h){}
    //ELSE YOU ARE THE OTHER PERSON AND YOU DO THE EXACT OPPOSITE OF ABOVE
    OK! Now that the code is out of the way. My problem.... Sometimes when I click on a button, the ineger value gets assigned to the ServerIn.reasline and funny symbols pop up in the other persons text area. And then when I try to type text in my text box after I get the wierd symbols into my chat text area, the CATCH (Exceptoin E) from my actionPerformed function that deals with sending the text gets activated and I see the dialog box that tells me there was an error.
    I THINK my error is in my run statement. I think everytime I write something, wether it be an integer or a text, the first .READLINE( ) that gets encountered in my run statement reads it. I think I have to have the WHILE(TRUE) statement or else it wont continuoulsy try to read in data.
    Can anyone tell me if I need to somehow make two threads, one that listens for the text and a seperate one that listens for the integer value?
    I hope this is a little bit more clearer than my last letters. Thanks for being patient with me.

  • Three questions about threads

    - can I use notify() before wait() or it doesn�t matter ?
    - what exactly the synchronized methods does, is it important to both method (notify() and wait()) and which is its relation to them ?
    - I was checking a program, reference is http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/, and I noticed that in the lines 122 and 123 it uses notify() before start(), is it possible ?

    - can I use notify() before wait() or it doesn�t
    matter ?
    - what exactly the synchronized methods does, is it
    important to both method (notify() and wait()) and
    which is its relation to them ?
    - I was checking a program, reference is
    http://developer.java.sun.com/developer/technicalArticl
    s/Networking/Webserver/, and I noticed that in the
    lines 122 and 123 it uses notify() before start(), is
    it possible ?
    - notify() will not block, "waiting" for a wait() to be issued. a notify() when no threads are wait()'ing will have no effect -- it will be "lost".
    - Synchronized just ensures that only one thread tries to notify or wait at a time.
    - You can call notify() at any time (whether or not there are multiple threads, or wait()'ing threads). There is no restriction.

  • Another question about threads

    Hi guys,
    I'm looking for a method to pause a thread for some time. I tried sleep(), but sleep() executes the run method after "sleeping".
    I just want a method to stop execution and resume at the same line of code. Is there a way I can do this?

    You have to call the wait on the object you are waiting on not the wait for the current thread.
    To get the monitor you have to synchronize on the queue
    eg
    run()
    synchronized(myQueue)
    if(myQueue.isEmpty())
    myQueue.wait();
    ....// process queue
    }// run()
    in the myQueue src code you need a method such as
    public void synchronized add(Object o)
    notifyAll(); // wakes up threads
    }

  • Another question about Thread! 'theJava' are prohibited!

    hi,guys!
    the code seems grown:)
    but it is still confused:~
    public class Test extends Thread{
         private boolean direct;
         Item item=null;
         public static void main(String argv[]){
              Item item=new Item(0);
              Test thread1=new Test(true,item);
              Test thread2=new Test(false,item);
              thread1.start();
              thread2.start();
         Test(boolean direct,Item item){
              this.direct=direct;
              this.item=item;
         public void run(){
              synchronized(item.part){
              /*synchronized(item){ here it works properly, for the item
              locked prevent any other thread's modification
              but why does 'item.part' take the same effect as above?
              what on earth does 'synchronized(x)' mean?
              does it lock the behaviors only on object x?
              could i lock member object of object x as above?
              for(int i=1;i<10;i++){
                   try{Thread.sleep(1000);}catch(InterruptedException ie){}
                   if(direct==true)
                        item.addValue();
                   else
                        item.reduceValue();
                   System.out.println((direct==true?"add value:":"reduce value:")+item.getValue());
    class Item{
         private int value;
         public Object part=new Object();
         Item(int i){
              value=i;
         public void addValue(){
              value++;
         public void reduceValue(){
              value--;
         public int getValue(){
              return value;
    thanks again.

    Here is the code in code tags, changed a little so I have Item as a static inner class (this has no effect on the running of the code either)..
    hi,guys!
    the code seems grown:)
    but it is still confused:~
    public class Test extends Thread {
        private boolean direct;
        Item item=null;
        public static void main(String argv[]) {
            Item item=new Item(0);
            Test thread1=new Test(true,item);
            Test thread2=new Test(false,item);
            thread1.start();
            thread2.start();
        Test(boolean direct, Item item) {
            this.direct=direct;
            this.item=new Item(0);
        public void run() {
            synchronized(item.part) {
                //* synchronized(item){ here it works properly, for the item
                //* locked prevent any other thread's modification
                //* but why does 'item.part' take the same effect as above?
                //* what on earth does 'synchronized(x)' mean?
                //* does it lock the behaviors only on object x?
                //*   could i lock member object of object x as above?
                for(int i=1;i<10;i++) {
                    try{
                        Thread.sleep(1000);
                    } catch(InterruptedException ie) { }
                    if(direct==true)
                        item.addValue();
                    else
                        item.reduceValue();
                    System.out.println((direct==true?"add value:":"reduce value:")+item.getValue());
        static class Item {
            private int value;
            public Object part=new Object();
            Item(int i) {
                value=i;
            public void addValue() {
                value++;
            public void reduceValue(){
                value--;
            public int getValue(){
                return value;
    }thanks again.
    Ok, the synchronized keyword takes an object as its parameter. This object is used by the objects monitor to make sure that no more than 1 thread may access it at a time for the duration of the synchronized block. Ok so far?
    The synchronized(item.part) works exactly the same way as synchronized(item) because part is a member of the item class. The monitor is just locking different objects, part happens to belong to item hence the effect of the lock is apparently the same.
    Variation 1. If the value for direct is true, sychronize on item. If false synchronize on item.part.
    Here is the code for you...
            synchronized((direct == true ? item : item.part)) {Run that and see what happens.
    Variant 2
    If you create 2 Item objects, assign the first one as you did before but the second 1 to the second Test instance then you will see that both threads now run side by side.
    Here is the code for that as well. Make sure that the synchronized code is the same as the original.
            Item item=new Item(0);
            Item item1 = new Item(0);
            Test thread1=new Test(true,item);
            Test thread2=new Test(false,item1);Hope this helps

Maybe you are looking for

  • Putting date and time in a spool file name for output

    I have bee trying to find this answer but don't know where to look: I want to take all or part of the date and/or time to create a unique filename on the fly for a spool file. Can someone point me in the right direction? I am using SQL*Plus.

  • High CPU usage with flash player

    hi ive just recently bought an emachines em250 netbook and when using most websites with flash it works ok normally around 30 - 40% cpu usage, however when i use itv player it increases the cpu usage to 95% meaning it runs slow. i am not running anyt

  • SD Business Process

    Hi, Can someone help me out in getting some docs where i can find the Bussiness Process in SD. Kindly let me know abt that?? Regards, Sekhar

  • Re-order point VB vs V1

    Dear SAP expert, I have confusion about the difference of VB (manual re-order point) and V1 (manual re-order point WITH external requirement). I have this material A Max stock level = 100 re-order point = 50 stock = 30 Reservation = 50 (today) lot si

  • Review Tracker Problems

    I set up some document reviews yesterday. I have Acrobat Pro 8. Most of my reviewers have Acrobat Reader 8 or 9. We're all on PCs. We have been using the review tool for over a year with no issues. I use the review that sends the link to the file tha