Thread noobie

I have absolutely no experience with threads.. I have read several tutorials but there's something I dont really get.
I have an application and its gui delays to load up due to a class that is responsible with connecting to an Imap server
so i have decided to use threads.. i hope you guys can help me out and point me in the right direction
My IMAP class has methods some of which are:
connect() //to connect to the server
getFolders() //to get Folders from the server
printFolders() //to print all the folders from the server
getMessages() // get all messages
close() // close connection
I am now trying to make this class run as a different thread..
Should i make this class implement runnable or would it be easier and cleaner to create a new class that implements runnable and constructs an object of my existing IMAP class.
Assuming it's easier to just create a new class.. i now have:
public class threadIMAP implements Runnable
public void run()
            IMAP imap = new IMAP();
            imap.connect();
            imap.getFolders();
            imap.printFolders();
        }From my GUI class now how would i call threadIMAP to run as a new thread?

Thanks for the help Peter.. could you give me some as to how i would use the ExecutorService?
Other than that.. i have this problem:
The following method creates threads that retrieve the Store objects of connections to an imap server
My problem is that this lines:
store = IMAP.getStore();
storeList.add(store);
run before the thread has reached the stage where it stores the object in the IMAPthread class
How would i get the thread to wait exactly the right amount of time, until the store object gets stored?
for (int i = 0;i<=accountsDetails.size()-1;i++)
         IMAPthread IMAP = new IMAPthread();
            IMAP.setUser(usernames);
IMAP.setPass(passwords[i]);
Thread t1 = new Thread(IMAP);
t1.start();
store = IMAP.getStore();
storeList.add(store);
public class IMAPthread implements Runnable {
private String theUser;
private String thePass;
private Store store;
public void run()
ImapServer imap = new ImapServer();
imap.setUser(theUser,thePass);
imap.connect();
store = imap.getStore();
public Store getStore()
return store;

Similar Messages

  • Noob Question: Problem with Persistence in First Entity Bean

    Hey folks,
    I have started with EJB3 just recently. After reading several books on the topic I finally started programming myself. I wanted to develop a little application for getting a feeling of the technology. So what I did is to create a AppClient, which calls a Stateless Session Bean. This Stateless Bean then adds an Entity to the Database. For doing this I use Netbeans 6.5 and the integrated glassfish. The problem I am facing is, that the mapping somehow doesnt work, but I have no clue why it doesn't work. I just get an EJBException.
    I would be very thankfull if you guys could help me out of this. And don't forget this is my first ejb project - i might need a very detailed answer ... I know - noobs can be a real ....
    So here is the code of the application. I have a few methods to do some extra work there, you can ignore them, there are of no use at the moment. All that is really implemented is testConnection() and testAddCompany(). The testconnection() Methode works pretty fine, but when it comes to the testAddCompany I get into problems.
    Edit:As I found out just now, there is the possibility of Netbeans to add a Facade pattern to an Entity bean. If I use this, everythings fine and it works out to be perfect, however I am still curious, why the approach without the given classes by netbeans it doesn't work.
    public class Main {
        private EntryRemote entryPoint = null;
        public static void main(String[] args) throws NamingException {
            Main main = new Main();
            main.runApplication();
        private void runApplication()throws NamingException{
            this.getContext();
            this.testConnection();
            this.testAddCompany();
            this.testAddShipmentAddress(1);
            this.testAddBillingAddress(1);
            this.testAddEmployee(1);
            this.addBankAccount(1);
        private void getContext() throws NamingException{
            InitialContext ctx = new InitialContext();
            this.entryPoint = (EntryRemote) ctx.lookup("Entry#ejb.EntryRemote");
        private void testConnection()
            System.err.println("Can Bean Entry be reached: " + entryPoint.isAlive());
        private void testAddCompany(){
            Company company = new Company();
            company.setName("JavaFreaks");
            entryPoint.addCompany(company);
            System.err.println("JavaFreaks has been placed in the db");
        }Here is the Stateless Session Bean. I added the PersistenceContext, and its also mapped in the persistence.xml file, however here the trouble starts.
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless(mappedName="Entry")
    public class EntryBean implements EntryRemote {
        @PersistenceContext(unitName="PersistenceUnit") private EntityManager manager;
        public boolean isAlive() {
            return true;
        public boolean addCompany(Company company) {
            manager.persist(company);
            return true;
        public boolean addShipmentAddress(long companyId) {
            return false;
        public boolean addBillingAddress(long companyId) {
            return false;
        public boolean addEmployee(long companyId) {
            return false;
        public boolean addBankAccount(long companyId) {
            return false;
    }That you guys and gals will have a complete overview of whats really going on, here is the Entity as well.
    package ejb;
    import java.io.Serializable;
    import javax.persistence.*;
    @Entity
    @Table(name="COMPANY")
    public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        @Column(name="COMPANY_NAME")
        private String name;
        public Long getId() {
            return id;
        public void setId(Long id) {
            this.id = id;
       public String getName() {
            return name;
        public void setName(String name) {
            this.name = name;
            System.err.println("SUCCESS:  CompanyName SET");
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Company)) {
                return false;
            Company other = (Company) object;
            if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "ejb.Company[id=" + id + "]";
    }And the persistence.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
      <persistence-unit name="PersistenceUnit" transaction-type="JTA">
        <provider>oracle.toplink.essentials.PersistenceProvider</provider>
        <jta-data-source>jdbc/sample</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
          <property name="toplink.ddl-generation" value="create-tables"/>
        </properties>
      </persistence-unit>
    </persistence>And this is the error message
    08.06.2009 10:30:46 com.sun.enterprise.appclient.MainWithModuleSupport <init>
    WARNUNG: ACC003: Ausnahmefehler bei Anwendung.
    javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
            at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:243)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:205)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:152)
            at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:225)
            at ejb.__EntryRemote_Remote_DynamicStub.addCompany(ejb/__EntryRemote_Remote_DynamicStub.java)I spend half the night figuring out whats wrong, however I couldnt find any solution.
    If you have any idea pls let me know
    Best regards and happy coding
    Taggert
    Edited by: Taggert_77 on Jun 8, 2009 2:27 PM

    Well I don't understand this. If Netbeans created a Stateless Session Bean as a facade then it works -and it is implemented as a CMP, not as a BMP as you suggested.
    I defenitely will try you suggestion, just for curiosity and to learn the technology, however I dont have see why BMP will work and CMP won't.
    I also don't see why a stateless bean can not be a CMP. As far as I read it should not matter. Also on the link you sent me, I can't see anything related to that.
    Maybe you can help me answering these questions.
    I hope the above lines don't sound harsh. I really appreciate your input.
    Best regards
    Taggert

  • How to get Grid by name in a non-ui thread - Windows Phone

    In my wp app, I am using silverlight 8.1 and
    I have this grid in my MainPage.xaml
    <Grid x:Name="LayoutRoot" Background="Transparent" HorizontalAlignment="Stretch">
    <Grid.RowDefinitions>
    I need to get it from another thread using this
    Deployment.Current.Dispatcher.BeginInvoke(() => {
    ... do some work on UI here
    how can I get it programmatically?
    I tried with MainPage.LayourRoot but it does not find LayoutRoot.
    Sorry for the noob question
    s

    MainPage.LayourRoot?

  • Thread Synchronization problem

    We guys are developing a P2P file sharing software(on LAN) and our program requires that we implement a multi-threaded client. I somewhere read on the forum about a multi threaded server but it doesnt work in my case (not on the client side.)The program runs properly when a single transfer is happening but if more then one file is getting downloaded the program seems to fall apart. Here's the code that provides the client side implementation of a file transfer.
    class Down implements Runnable     
                         DataOutputStream dataOutput;     
                         BufferedInputStream bufferedInput;     
                         FileOutputStream fileOutput;
                         Socket down;
                         public void run()
                                      try
                                              int data=0;
                                              long i=0;
                                              down=new Socket(user,9999);
                                              dataOutput=new DataOutputStream(down.getOutputStream());  //The following two lines send the file path to the server, to make the server's job easier rather than the server going for a file search
                                              String msg=path.replace('\\','/');   dataOutput.writeUTF(msg);     
                                              dataOutput.flush();
                                              bufferedInput=new BufferedInputStream(down.getInputStream());
                                              fileOutput=new FileOutputStream(new File(path));
                                              while (data != -1)
                                                       data=bufferedInput.read();
                                                       fileOutput.write(data);
                                                       fileOutput.flush();
                                                       i++;
                                                       System.out.println("Transferring "+i);
                                              System.out.println("File Transfer Done");
                                              done=true;
                                     catch (Exception e)
                                                 e.printStackTrace();
                                     } Can you guys point out specifically where my program would need synchronization, since im a noob when it comes to threads. Thanks

    Thanks ejp for those prompt replies .......yeah the path and the down socket) variables are unique...... from what i see on my network .... the server side of the transfer happens at a faster rate i.e the final println line printing the transferred byte (at the end of the while loop) is much ahead at the server side of the transfer ...... the client lags far behind in this regard...... and from what i know Lan connections support upto 100Mbps so there's no question of data loss..... one of the reasons i opted for byte by byte transfer....... just to be on the safer side...... and yes ill make that small change in my program

  • Suggest a thread or search term for me...

    I'm a total NOOB with X-Code, but today I was able to successfully create an installation package using PackageMaker's assistant. Way too easy.
    The path to which I want to copies files is actually WITHIN the new iWeb application:
    ...../iWeb.app/Conents/Resources/Frames/
    Because not everyone has their applications installed to /Applications/ I want the installer to "find" iWeb.app by itself and install to the path I specify beyond that. I just don't know how to specify this in path format...
    Is there a good thread for this or can someone suggest a search term. The search functionality for these forums is pretty weak.
    Thanks - Suzanne

    I'm a total NOOB with X-Code, but today I was able to successfully create an installation package using PackageMaker's assistant. Way too easy.
    The path to which I want to copies files is actually WITHIN the new iWeb application:
    ...../iWeb.app/Conents/Resources/Frames/
    Because not everyone has their applications installed to /Applications/ I want the installer to "find" iWeb.app by itself and install to the path I specify beyond that. I just don't know how to specify this in path format...
    Is there a good thread for this or can someone suggest a search term. The search functionality for these forums is pretty weak.
    Thanks - Suzanne

  • The Official Hello Everyone Thread

    Non-Moderator Note: This is the unofficial "I'm a newbie to Arch" thread. Post here if you'd like to say hello to the friends you're going to make here, or to say hello to a friend u persuaded to join the wonderful world of Arch Linux. Feel free to explain your reasons.
    Not much sense in posting if you just want to post that "Arch Rocks" (in whatever form of leetspeak you prefer, of course).
    Naturally, we hope this thread will be the longest one in the forum history! :-)
    below (if u scroll for a short while) you'll find some the first hello of this thread
    and prolly some leet comments from ppl already using arch for a while
    hello
    ps. dont be afraid afraid to post. afterall everyone like noobs (mmm blood)
    Last edited by dolby (2007-04-27 21:04:41)

    Well, I guess I should say hello
    I've been using Arch for about six months now, and thought I should finally post something.
    I started using linux about 18 months ago, but I consider myself pretty much a n00b.  For the first year I was the queen of distro hoppers, switching distro every couple of months (a few times it was every couple of weeks).  I have a cruddy old laptop and wanted something that ran at a half-decent speed.  I'd heard that Arch was fast, but also very difficult to install.  I thought it would be too difficult for me, but decided to give it a shot anyway.  I followed the instructions in the wiki and got it working first time. I was amazed at how simple it was, and I felt as though I had a slightly better understanding of what's going on under the hood.
    I've never posted before, as whenever I've had a problem, I've managed to solve it by searching the forum and/or googling.  I've never answered anyone else's questions as most of them are way over my head, even in the Beginners forum :-D  Whenever I read here, I wind up feeling like an idiot!
    Since first installing Arch, my distro-hopping compulsion has gone completely.  I love Arch and can't imagine switching to anything else.

  • Uncyclopedia Arch Linux Entry - Ubuntu Noobs

    Seeing as Arch's community has a relatively significant population of (ex?) Ubuntu Noobs, I felt the urge to include a little splurge about it on Uncylopedia. The fact that I wrote it is a bit ironic, because I am an ex Ubuntu noob myself (used it for almost a year before I called it quits).
    I'm posting this thread to see if my statements actually resonate with the Arch community or not really - and if anyone has serious objections to it I'll remove it. But hey, it's just a joke...
    http://uncyclopedia.org/wiki/Archlinux#Ubuntu_Noobs
    edit: I doubt this is worth noting, but this is my first time using uncyclopedia so I hope I really hope you like it.
    Last edited by vsk (2008-08-11 15:53:44)

    vsk wrote:I'm posting this thread to see if my statements actually resonate with the Arch community or not really - and if anyone has serious objections to it I'll remove it. But hey, it's just a joke...
    Methinks you don't quite yet have the right mindset to contribute to Uncyclopedia.
    (head here or here for some good pointers to get you started)

  • Concurrency noob needs strategies not just facts.

    I'm a concurrency noob. I've read up on it quite a bit I understand most of it but I've written this program and I'm completely clueless as to how to get my time sensitive data threaded correctly. I've included a vastly oversimplified version just for this post. Look at it like a midi sequencer where, at the same time, you have data being edited via GUI and played back by a clock. Of course, this is a simplification, but in the real version, it sometimes happens that the GUI part of the program can be so taxing that it pushes the timed part out of wack. Can someone point me in the right strategic direction?
    This is how the unthreaded program is structured. I tried to make it as close to MVC as possible.
    import java.util.*;
    public class TryThis {
    /*main method simulates the program running*/
         public static void main(String args[]) {
              InfoPlayer myInfoPlayer = new InfoPlayer(); // an object to do time sensitive operations on global data
              InfoEditor myInfoEditor = new InfoEditor(); // an object to send events to edit global data
              InfoDisplayer myInfoDisplayer = new InfoDisplayer(); // an object to display any changes made to global data
              // time sensitive information requested
              myInfoPlayer.string();
              myInfoPlayer.integer();
              // user alters data
              myInfoEditor.setString("joooo");
              myInfoEditor.setInt(11111);
              // time sensitive information requested
              myInfoPlayer.string();
              myInfoPlayer.integer();
              // user alters data
              myInfoEditor.setString("korea");
              myInfoEditor.setInt(3333);
              // time sensitive information requested
              myInfoPlayer.string();
              myInfoPlayer.integer();
    /* 1: receives instructions on how to edit info
    * 2: edits info
    * 3: sends same instructions out as an event to update displays*/
    class GlobalReference {
         static private InfoHolder myInfo = new InfoHolder();
         static protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList();
         public static InfoHolder getMyInfo() {
              return myInfo;
         static public void doMyEvent(MyEvent me) {
              if (me.getChangeStringOrInt() == MyEvent.STRING) {
                   myInfo.setString(me.getString());
              } else {
                   myInfo.setInt(me.getInt());
              fireMyEvent(me);
         static public void addMyEventListener(MyEventListener listener) {
              listenerList.add(MyEventListener.class, listener);
         static void fireMyEvent(MyEvent evt) {
              Object[] listeners = listenerList.getListenerList();
              for (int i = 0; i < listeners.length; i += 2) {
                   if (listeners[i] == MyEventListener.class) {
                        ((MyEventListener) listeners[i + 1]).myEventOccurred(evt);
    //The info
    class InfoHolder {
         String string = "default String";
         int integer = 0;
         public String getString()
              {return string;     }
         public void setString(String myString)
              {this.string = myString;}
         public int getInt()
              {return integer;}
         public void setInt(int myInt)
              {this.integer = myInt;}
    //Simulates program displaying data,  listens for updates
    class InfoDisplayer implements MyEventListener {
         public InfoDisplayer() {
              GlobalReference.addMyEventListener(this);
         public void myEventOccurred(MyEvent evt) {
              if (evt.getChangeStringOrInt() == MyEvent.STRING) {
                   System.out.print("InfoDisplayer:\t\t" + evt.getString() + "\n");
              } else {
                   System.out.print("InfoDisplayer:\t\t" + evt.getInt() + "\n");
    //simulates user using the UI to edit data
    class InfoEditor {
         public void setString(String s) {
              /* event says set global string to source s */
              MyEvent temp = new MyEvent(s, MyEvent.STRING);
              GlobalReference.doMyEvent(temp);
         public void setInt(int i) {
              /* event says set global int to source i */
              MyEvent temp = new MyEvent(i, MyEvent.INT);
              GlobalReference.doMyEvent(temp);
    //Simulates calls for time sensitive(read clocked) actions on global data.
    class InfoPlayer {
         public void string() {
              System.out.print("InfoPlayer:\t\t"
                        + GlobalReference.getMyInfo().getString() + "\n");
         public void integer() {
              System.out.print("InfoPlayer:\t\t"
                        + GlobalReference.getMyInfo().getInt() + "\n");
    /* 1 instructs static info repository on how to edit data,
    * 2 then gets send by static repository to update any listeners
    class MyEvent extends EventObject {
         static boolean STRING = false, INT = true;
         boolean changeStringOrInt = STRING;
         public MyEvent(Object source, boolean changeStringOrInt) {
              super(source);
              this.changeStringOrInt = changeStringOrInt;
         public String getString()
              {return (String) source;}
         public int getInt()
              {return (Integer) source;}
         public boolean getChangeStringOrInt()
              {return changeStringOrInt;}
    /*describes any object that might be used to display global data*/
    interface MyEventListener extends EventListener {
         public void myEventOccurred(MyEvent evt);
    }Edited by: Mat on May 10, 2009 11:34 PM
    Edited by: Mat on May 10, 2009 11:47 PM

    Can someone point me in the right strategic direction?That's the only question I can see. It's not much of a question, is it? I suggest you state your problem in more detail. And I don't think the code really helps much at this stage.

  • Java thread synchronized block

    i am still a noob comes to thread and synchronized.
    i heard people said that i shouldn't synchronized on "mySet" because "mySet" is getting modified in the synchronized block.
    is this true?
    or should i use a different object to synchronized the block. what's the advantage or disadvantage to use a different object to synchronized the block.
    thanks
    public class Test {
      final Set mySet = new HashSet(); 
      final Map myMap = new HashMap();
      public void add(Object o) {
        synchronize(mySet) {
          mySet.add(o);
          myMap.add(o);
      public void clear(){
        synchronize(mySet) {
          mySet.clear();
          myMap.clear();
    }

    yaliu07 wrote:
    i am still a noob comes to thread and synchronized.
    i heard people said that i shouldn't synchronized on "mySet" because "mySet" is getting modified in the synchronized block.
    is this true? No, that's not a reason not to sync on that object. In fact, in some cases it's a reason why you should sync on that object.
    Most of the time it doesn't matter which object you sync on, as long as all the relevant blocks are synced on the same object. There are a couple of considerations to keep in mind though that might affect the choice of object.
    In some cases, you want to sync on an object that's not exposed to the outside world, for instance a private Object member variable that exists only to be a lock. The reason for this is that if you sync on something that's exposed to the outside (such as "this", which is what gets synced on when you declare a non-static method as synchronized), then other code might also sync on that object, causing deadlock or thread starvation.
    In other cases, you DO want to expose the object, so that you can use it to ensure that other code and your synced code only enter the critical sections one thread at a time. For instance, in Collections.synchronizedXxx() methods, the return object's methods are all synced on "this", and any code that iterates over that collection must also sync on that object, so that the iteration code and the collection object's own code don't step on each other's toes.
    Much of the time, however, the choice of an object to sync on is just one that's convenient and logical for the humans writing and reading the code.

  • Noob seeks a learning partner in NYC

    might there be a guru -- or aspiring guru -- in NYC who is willing to partner with a conscientious noob for commensalism, or for mutual learning?

    Moderator advice: Don't double post. The other thread you started with the same request has been deleted.
    db

  • MOVED: (Noobie OCer) FSB down throttled despite manual settings?

    This topic has been moved to Overclockers & Modding Corner.
    (Noobie OCer) FSB down throttled despite manual settings?

    1. System Specs which I thought followed forum policy and had enough information are afaik now exactly as per forum policy as stated here: https://forum-en.msi.com/index.php?topic=64858.0 . Please let know if I've missed anything.
    2. I read the sticky post and there's, no reference to this problem I could see. Sorry if I should have replied in that thread, however my fuzzy logic moved me to post originally in the Overclocking forum because I wanted to overclock and it's late... 
    3. I flashed the BIOS specifically because I had a Venice core and dual channel wouldn't work. Yes, I set optimized defaults after flashing.
    If I've boobed by creating a new thread at this late hour, please delete it and I'll add a post to the 9.1 BIOS sticky thread.

  • Playing with threads, fun, but I need questions answered

    Ok so I am learning multi-threading. My implementation is to use a runnable and Executor interface. The run() method can not be overloaded so my question is, how can I run 2 threads executing different code?

    Well as I write, too much information for me. Sorry, but I am not a developer, not a Swing programmer, not anything and on the level of noob tinkering with stuff because I want to learn it and it has not been taught to me yet. What is proposed is simply beyond what I am doing right now and I think mostly stabbing in dark to jazz up a program beyond my programming capabilities atm. So I thought I could come here and get the buzz on working through my multithread tinkering.
    Anyway, I have tried using sleep(), tried alternating my two lazy threads but I think I am doomed to have to put this off till semester is over. I can thread well now on a basic level but when I run the following code in 2 threads simultaneously, they don't share, one hogs and tells the other to shut up:
    public void run()
            try
                    Thread.sleep(1000);
                    System.out.println(toString());
                catch(Exception haha)
            for (seconds = 0; seconds < 5; seconds++)
                System.out.println(toString());
    public void run()
            int count = 2;
            do
                int nextPoisson = linkedList.Poisson(expectedValue);
                for ( int i = 0; i < nextPoisson; i++)
                    linkedList.enQueue(nextPoisson + "", 0);  // enQueue the node
                    count--;
                try
                    Thread.sleep(2000);
                catch(Exception haha)
                linkedList.setTime();        // set the wait time
            while(count > 0);
        }Meh been a blast with this and even if it doesnt work like I want still nice to expose myself.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Slight problem with threads....

    Hello,
    Just started learning threads a few days ago.. my objective is to move an oval from left to right, then right to left, back and forth and so on.. however, it wont work, the source code i have below seems logical, but it doesnt fulfill my objective..
    // The "MovingCircleUsingThreads" class.
    import java.applet.*;
    import java.awt.*;
    public class MovingCircleUsingThreads extends Applet implements Runnable
        int x = 0;
        Thread t;
        public void init ()
            t = new Thread (this);
            t.start ();
        } // init method
        public void run ()
            try
                while (true)
                    repaint ();
                    Thread.sleep (20);
            catch (Exception e)
        public void paint (Graphics g)
            int speed = 10;
            Dimension d = getSize ();
            g.fillOval (x, d.height / 4, 50, 50);
            x = x + speed;
            if (x + 50 == d.width)
                speed = -10;
    } // MovingCircleUsingThreads classI think the paint method is wrong, but it all seems logical.. x starts off in the left side, moves to the right side by 10, when x + 50 == d.width, the oval is at the right edge, and speed = -10, so it should be moving to the left by 10, but instead, the oval disappears.. :( can anyone help?
    public void paint (Graphics g)
            int speed = 10;
            Dimension d = getSize ();
            g.fillOval (x, d.height / 4, 50, 50);
            x = x + speed;
            if (x + 50 == d.width)
                speed = -10;
        }

    public void paint (Graphics g)
    int speed = 10;
    Dimension d = getSize ();
    g.fillOval (x, d.height / 4, 50, 50);
    x = x + speed;
    if (x + 50 == d.width)
    speed = -10;
    }So you are setting speed to -10, and then you are
    leaving paint?
    Can not see this having any impact on processing...Im setting speed to -10 because I want the oval to go left.... But it wont, after the oval goes from left to right, it disappears..
    Try changing the following:
    if (x + 50 == d.width)
    speed = -10;to
    if (x + 50 >= d.width)
    speed = -10;
    Tried changing that before, oval disappears after it goes to right side :\

  • A problem with Threads and loops.

    Hi, I have some code that needs to be constantly running, like while(true)
          //code here
    }However, the code just checks to see if the user has input anything (and then if the user has, it goes to do some other stuff) so I don't need it constantly running and hogging up 98% of the CPU. So I made my class (which has the method that needs to be looped, call it ClassA) implement Runnable. Then I just added the method which needed to be looped into the public void run()
    I have another class which creates an instance of the above class (call it ClassB), and the main(String[] args) is in there.
    public static void main(String[] args)
              ClassA test = new ClassA();
              Thread thread = new Thread(test.getInstanceOfClassA());
              thread.start();
              while(true)
                           //I do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...) but I can't think of away to get it to run - sleep - run -sleep forever. Can someone help me?

    Hi, I have some code that needs to be constantly
    running, like while(true)
    //code here
    }However, the code just checks to see if the user has
    input anything (and then if the user has, it goes to
    do some other stuff) so I don't need it constantly
    running and hogging up 98% of the CPU. Where does the user input come from. Are you reading from an InputStream? If so, then your loop will be blocked anyway when reading from the InputStream until data is available. During that time, the loop will not consume processor cycles.
    public static void main(String[] args)
              ClassA test = new ClassA();
    Thread thread = new Thread(test.getInstanceOfClassA());I have never seen this idiom. If ClassA instanceof Runnable, you simply write new Thread(test).
              thread.start();
              while(true)
    //I do not know what to put
    do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...)Yeah, why would you want to call it more than once given that you have an infinite loop in ClassA.run()?
    Harald.
    Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

Maybe you are looking for