Making thread

Hi , everyone , i have a homework to do , i want to make this SSWindow class as a thread or implements a runnable method , but i have no idea to solve this , can anyone help me please ?
// SSWindow class
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
* The Slide Show window
public class SSWindow extends JWindow implements
ActionListener, FileFilter , MouseListener {
/** The image label */
JLabel imageLabel;
/** The parent */
JFrame parent;
/** The directory */
String direc;
/** List of files in the directory */
String[] filenames;
/** Delay in milliseconds */
int delay;
/** Counter */
int count;
/** The timer that displays the Slide Show */
Timer timer;
/* Constructor */
public SSWindow(JFrame par, String direc, float seconds) {
     super(par);
     parent = par;
     this.direc = direc;
     delay = (int)(seconds*1000);
     // Add label to center of screen
     Container back = getContentPane();
     imageLabel = new JLabel();
     back.setBackground(Color.black);
     back.add(imageLabel);
     imageLabel.setVerticalAlignment(JLabel.CENTER);
     imageLabel.setHorizontalAlignment(JLabel.CENTER);
     setSize(getToolkit().getScreenSize());
     setVisible(true);
     // Get the names of the files
     File[] files = (new File(direc)).listFiles(this);
     filenames = new String[files.length];
     for (int i=0; i<filenames.length; i++) {
          filenames[i] = files.toString();
     count = -1;
     timer = new Timer(delay, this);
     timer.start();
} // End constructor
/** Function that changes the image */
public void updateImage() {
     try {
          imageLabel.setIcon(new ImageIcon(filenames[count]));
          imageLabel.addMouseListener(this);
     } catch(Exception ex) {
          timer.stop();
          SSWindow.this.dispose();
          parent.setVisible(true);
} // End updateImage()
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mousePressed(MouseEvent e)
     timer.stop();
     parent.setVisible(true);
     SSWindow.this.dispose();
public void mouseReleased(MouseEvent e)
public void actionPerformed(ActionEvent e) {
     count++;
// If we have gone past the last file,...*/
// return to beginning.
     if (count > (filenames.length-1)) {
          count = 0;
     updateImage();
} // End actionPerformed()
public boolean accept(File file) {
     String filename = file.toString();
     if (filename.endsWith(".tiff") ||
     filename.endsWith(".tif") ||
     filename.endsWith(".gif") ||
     filename.endsWith(".jpeg") ||
     filename.endsWith(".jpg")) {
          return true;
     } else {
          return false;
} // End accept()
} // End class SSWindow
// Here is the main class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
* The Slide Show's Opening Screen
public class SSFrame extends JFrame {
JTextField direcText, delayText;
JFileChooser fc;
static final String
WINTITLE="Kengs' Slide Show Viewer",
DIRECTORY="Directory : ",
BROWSE="Browse...",
DELAY="Delay : ",
TIME="2",
SECONDS="seconds",
START="Start SlideShow!",
ADVANCED="Advanced...",
ABOUT="About...",
EXIT="Exit";
public static void main(String args[])
     SSFrame ss = new SSFrame();
} // End main()
public SSFrame() {
// Set the title
setTitle(WINTITLE);
     Container back = getContentPane();
     back.setLayout(new GridLayout(0,1));
     back.add(new JLabel(new ImageIcon("images/kss.gif")));
     fc = new JFileChooser();
     fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
     JPanel p1 = new JPanel();
     p1.add(new JLabel(DIRECTORY, new ImageIcon("images/directory.gif"), JLabel.CENTER));
p1.add(direcText = new JTextField(20));
     JButton browseButton = new JButton(BROWSE, new ImageIcon("images/browse.gif"));
     browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(SSFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
          direcText.setText(fc.getSelectedFile().toString());
     p1.add(browseButton);
     back.add(p1);
     JPanel p1e = new JPanel();
     p1e.add(new JLabel(DELAY, new ImageIcon("images/delay.gif"), JLabel.CENTER));
     p1e.add(delayText = new JTextField(TIME, 5));
     p1e.add(new JLabel(SECONDS));
     back.add(p1e);
     JPanel p2 = new JPanel();
     JPanel butPanel = new JPanel();
     butPanel.setBorder(BorderFactory.createLineBorder(Color.black));
     JButton startButton = new JButton(START, new ImageIcon("images/start.gif"));
     startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
          SSFrame.this.hide();
          SSWindow s = new SSWindow(
          SSFrame.this, direcText.getText(),
          new Float(delayText.getText()).floatValue()
     butPanel.add(startButton);
     p2.add(butPanel);
     JButton aboutButton = new JButton(ABOUT, new ImageIcon("images/about.gif"));
     aboutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
          // Should display message box here
     p2.add(aboutButton);
     JButton exitButton = new JButton(EXIT, new ImageIcon("images/exit.gif"));
     exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
          System.exit(0);
     p2.add(exitButton);
     back.add(p2);
     addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
     pack();
     setVisible(true);
} // End constructor
} // End class MainFrame

public class MyRunnable implements Runnable{
public static void main(String[] args){
Thread t = new Thread(new MyRunnable());
t.start();
public void run(){
System.out.println("Dead thread walking");
}I always overwrite start() and stop()
http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
This means I have control in a consistent manner when and how I want.
ie:
public class MyClass implements Runnable
static Object waitObject = new Object();
Thread task;
pubic void start()
   task = new Thread(this);
   task.start();
pubic void stop()
   task = null;
public void run()
Thread controlThread = Thread.currentThread();
   while(controlThread == task)
          ///do something.
           synchronized waitObject
                try
                     waitObject.wait(20);   //. preempt (Not sleep) for 20 MS
                 }                     // Set to taste.   proper waits / synchronization
                 catch(InterruptedException ie)  // eliminates races
}

Similar Messages

  • Calling thread.start() more than once concurrently

    Hi, I got a simple doubt that may feel awkward or absurd to people who are well versed in the java threading concepts. I just thought of it and as I couldn't get an easy answer I am posting this.
    Consider a class that implements the runnable interface. The run() method of the class is implemented with just a System.out.println(). If I make an instance of this class, say 't' in the main method and calling t.start() susequently twice or thrice; an illegal ThreadStateException will be thrown. The code snippet is as follows:
    ThreadTest t = new ThreadTest();
    t.start();
    t.start();
    It is understood that state of the thread object is changed to run state and so, if it is again started, it must be thrown. So if I put a Thread.sleep() inbetween these two subsequent calls assuming that the main method thread will be sleeping. So there is sufficient time for the first thread to terminate and then only the second will start - still the same exception is being thrown. I tried putting the synchronized qualifier for run too, still no effect - the same only happening. Why the java thread object is made in such a way that once the thread changes it state from Runnable to Running and then finally to dead state, it can be restated back to Runnable state, such that the start() method can be called again. Is it possible or not? Please post your comments.

    As ejp says you can't start a thread more than once - even if it has already terminated after the first start.
    By making threads a one-shot it simplifies reasoning about them: you don't have to wonder whether a second start() will work or not, depending on whether the thread has completed its first "incarnation". It also makes it easier to ensure thread resources are reclaimed. It also avoids semantic issues like whether anything about the thread is "carried over" across incarnations.
    This might seem a limitation but there are many ways around it - simply don't let the thread terminate. Whatever control structure you would enforce by re-starting the thread can be emulated without letting the thread terminate in between "executions".

  • Thread Objects?

    Hi, I need help on making thread objects. I have some code similar to this. It runs as an applet.
    //ThreadTest
    import java.awt.*;
    import java.applet.Applet;
    public class ThreadTest extends Applet {
         public void init() {
              new ThreadObject().start();
    public void paint(Graphics g) {
    g.drawstring(""+i,50,50)
    //this is a new file
    //ThreadObject
    public class ThreadObject extends Thread {
         public ThreadObject() {
              for (int i=0;i>9;i++) {
                   System.out.println(i);
    Im trying to make this thread just dispay the numbers 1-9 (I understand that it should only print 9 because it prints i to the coordinates 50,50, so the numbers will overlap)
    but the screen just stays grey. Ive tried changeing the programs tons of times, but I cant get it to work. Please help!

    Ok, first of all, when you extend Thread the code that will be run should be put in the run() method, second, the variable i is only relevent within the for loop, and has nothing to do with the applet, so your line g.drawString(""+i, 50, 50) will not draw i onto the applet, third, there is no code to repaint the applet when you make changes. Take a look at this... I haven't tested it, but it should be about right: //ThreadTest
    import java.awt.*;
    import java.applet.Applet;
    public class ThreadTest extends Applet {
    int var = 0; //This varable holds the number to display
      public void init() {
        new ThreadObject(this).start(); /* I'm having this object send a refference
                                        // to itself so the thread has a way to
                                        // call the repaint method */
      public void update(int i) {
        var = i;
        repaint();
      public void paint(Graphics g) {
        g.drawstring("" + var,50,50)
    public class ThreadObject extends Thread {
    Applet parent;
      public ThreadObject(Applet p) {
        parent = p;
      public void run() {
        for (int i=0;i>9;i++) {
          parent.update(i);
          try {
            Thread.currentThread().sleep(500);/*I'm having the Thread sleep
                                              //for 1/2 second between numbers
                                              */so you can see the numbers change
          } catch(Exception e){System.out.println("Exception: " + e);}
    }Like I said, I haven't tested this, so there may be some little problem, but I think that should be about it.
    Hope it helps
    webaf409java

  • Multi-processor Multi-Threaded deadlock

    Hi all-
    I've posted this over at jGuru.com and haven't come up with an effective solution but I wanted to try here before I reported this as a bug. This deals with kicking off many threads at once (such as might happen when requests are coming in over a socket).
    I'm looking for a way to find out when all of my threads have finished processing. I have several different implementations that work on a single processor machine:
    inst is an array of 1000+ threads. The type of inst is a class that extends threads (and thus implements the runable interface).
    for (i = 0;i<Count;i++)
    inst[ i ].start()
    for (i = 0;i<Count;i++)
    inst[ i ].join();
    however this never terminates on a multiprocessor machine. I've also tried an isAlive loop instead of join that waits until all threads have terminated until it goes on. Again, this works on the single processor but not the multi-processor machine. Additionally someone suggested a solution with a third "counter" class that is synchronized and decremented in each thread as processing finishes, then a notifyAll is called. The main thread is waiting after it starts all the threads, wakes up to check if the count is zero, and if it's not it goes back to sleep. Again this will work on the single processor but not the multi-processor.
    The thread itself ends up doing a JNI call which in turn calls another DLL which I just finished making thread safe (this has been tested via C programs). The procedures are mathematically intensive but calculation time is around half a second on a P3 800Mhz.
    Any help on this is greatly appreciated. My next step will likely be tearing down the application to exclude the calculating part just to test the JVM behavior. Is there a spec with the JVM behavior on a multi processor machine, I haven't seen one and it's hard to know what to expect from join() (joining across to processors seems like wierd concept), getCurrentThread() (since 2+ threads are running at the same time), etc.

    My next step will likely be tearing down the application to
    exclude the calculating part just to test the JVM behavior.Sounds like a really good idea.
    Is there a spec with the JVM behavior on a multi processor machine, The behaviour of threads is defined in the specs.
    You might want to check the bug database also. There are bug fixes for various versions of java.

  • My FaceTime on my iPad mini stopped working help

    My iPad mini face time stopped working help

    Given how many people are making threads on the issue I think it's safe to guess that the issue is a systemic one on Apple's end. There's not much users can do but wait it out unfortunately.

  • A doubt in mutilthreading behaviour

    Dear experts,
    I have created a multithreading program in java.When i click a start button,i
    see helicopter moving across the sky.I click another button and a new thread get
    created and this time i see two helicopters flying.In this way as i keep pressing
    start number of helicopters are increasing.
    But i find as i keep on looking at taskbar CPU usage is increasing everytime i click on
    start.And after clicking about 50 times ,CPU show 100% usage and virtual memory come
    in function.This time more than 50 helicopters are visible flying.
    With so many helicopters ,speed of each helicopter is very very slow and looks as if system
    is in too much load.Is this behaviour normal in multithreading for java ?.

    My guess is you have busy loops somewhere. In any case this is far from normal behavior. Are you making threads sleep until it is time for a helicopter to move again?
    You may want to invest some time into studying timers. With those you can do updates at specific intervals, leaving all the sleep logic to Java.

  • My mini iPad will not connect when I facetime

    Help

    Given how many people are making threads on the issue I think it's  safe to guess that the issue is a systemic one on Apple's end. There's  not much users can do but wait it out unfortunately.

  • Using ServletContextListener for background process in tomcat, problems?

    Hi, I am building a web app using mojarra 1.2, hibernate 3.2, mysql 5 and tomcat 6. Currently, there's a need to run a background process every hour to:
    1) query the database
    2) process information
    3) send emails to (big) list of individuals when matched
    4) update database
    5) must happen during business hour
    For now, my approach to this problem is to hook a Timer object inside a class implements ServletContextListener. So that every hour during business hour will process the steps above when Tomcat started until someone shut down shut down Tomcat or when it crash (hopefully that won't happen).
    I read a few articles, they claimed this is not a good approach because in a managed environment, background thread like this won't be in the scope of the container.
    Due to certain reasons, we can't deploy this part as a separate daemon (e.g: jsvc) yet. We'll need to wait for few other things to occur before can we deploy a full daemon services.
    The question for this post is: What are some of the potential problems we will be dealing with when running background thread like this in tomcat? What are some of the things we'll need to watch out for before real problems arise (e.g size of db connection, # of concurrent process, etc) what are some other pitfalls other experienced when deploying background thread in tomcat?
    We hope this solution will be able to handle what needs to be done until our daemon service is ready.
    Thank you for your opinions

    You can try this.. Which gives more grip... in making threads etc..
    Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
    import static java.util.concurrent.TimeUnit.*;
    class BeeperControl {
    private final ScheduledExecutorService scheduler =
    Executors.newScheduledThreadPool(1);
    public void beepForAnHour() {
    final Runnable beeper = new Runnable() {
    public void run() { System.out.println("beep"); }
    final ScheduledFuture<?> beeperHandle =
    scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
    scheduler.schedule(new Runnable() {
    public void run() { beeperHandle.cancel(true); }
    }, 60 * 60, SECONDS);
    }

  • Issue with internal JMS queue

    Hi,
    We discovered following issue with Netweaver version:
    SAP EP 6.0 ON WEB AS 6.20
    J2EE version:
    Cluster-Version: 6.40   PatchLevel 106831.313
    Build-On:Thursday, October 26, 2006 18:56 GMT
    Perforce-Server:
    Project-Dir:JKernel/630_VAL_REL
    JKernel Change-List:106831
    Build machine:SAPInternal
    Build java version:1.3.1_18-b01 Sun Microsystems Inc.
    SP-Number: 19
    Source-Dir: D:\make\engine\630_VAL_REL\builds\JKernel\630_VAL_REL\archive\dbg
    During sending messages into internal JMS queue we sent messages bigger than 1MB. After that, JMS queue was not able to process any other messages even if it was smaller than 1MB. Same issue occured if there was more smaller messages sent in short time (e.g. in 2 seconds). We don't have any significant error message in any log.
    See information thath we have found in dump stack trace file (ix.log):
    "SAPEngine_Application_Thread[impl:3]_25" prio=5 tid=0x0000000101f5ebf0 nid=0x37 in Object.wait() [fffffffe0bdfd000..fffffffe0bdff8b0]
    at java.lang.Object.wait(Native Method)
    - waiting on <0xfffffffe2ebfa1b8> (a java.lang.Object)
    at java.lang.Object.wait(Object.java:429)
    at com.sap.jms.client.memory.MemoryManager.allocate(MemoryManager.java:132)
    - locked <0xfffffffe2ebfa1b8> (a java.lang.Object)
    at com.sap.jms.client.memory.MemoryManager.allocateMemoryForBigMessage(MemoryManager.java:92)
    - locked <0xfffffffe2ebfa1b8> (a java.lang.Object)
    at com.sap.jms.client.session.Session.processFinalMessage(Session.java:1732)
    at com.sap.jms.client.session.Session.run(Session.java:675)
    at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
    at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    which indicates to us that initializing of memory is locked.
    Please let us know:
    -if there is any log which indicates this behaviour without making thread dump
    -which limits must be fulfilled to process messages without this error
    -how to unblock this lock for processing correct messages without restarting NW - or if there is any predefined timout which kill this locked session and disable uncorrect message
    -how to manage records in bc_jmsqueue table for removing big messages from queue if there were loaded already
    -how to stop application which caused this problem. If we try to stop it through standard stop_App, application stays in Stopping mode forever.
    This problem occured in test environment and also in productive environment using the same SAP NW. Now - we do not have any work around solution..... therefore periodically we need to restart SAP NW....
    Thx for any suggestions.....

    Hi,
    We are also facing the same problem of restarting the SAP NW each time, if you have found the solution, please let me know.
    Thx in advance.
    Ramanath

  • 3 minute slide show

    Just made a 3 minute slide show using a song from iTunes. Exported it as a quicktime movie. Tried running it on another computer and the song would not play. The error message said my computer did not have permission to play the song! Apple you have got to be kidding me!! If anyone has a work around please post!

    I believe you're able to authorize up to 5 Macs/computers to play those protected songs. How, I don't know as I don't have any iTMS purchased tracks but check in the iTunes forum. There's a way to authorize the other Mac or PC (probably has to have iTunes installed though) so it will play them.
    It's not Apple's fault. They are just abiding to the anti piracy laws and contracts that they have had to enter into. Get mad at the Music industry.
    P.S. making thread titles like that is not going to get you lots of enthusiastic help around here.

  • 7610 Enhancement settings?

    First off, where is the search button? I hate making threads when something is probably already covered... anyways:
    2 days ago, my phone had its Enhancement settings activated. It has the little head phone icon on the top right. I didn't turn it on or anything, nor do i even have head phones connected. The problem with this is, the phone no longer produces sound (other than ringing) when making or answering a call. It works fine with the head phones.
    Other times the phone will have a messege come up and say "Enhancement not supported" and everything would be fine again.
    It goes back and forth between the two modes and there dosn't seem to be an option to turn Enhancement off, only change what type of enhancement.
    can anyone assist me with this problem?

    i updated my software. two main problems. no headset recognition - i went to shops and tries out. nothing works.
    other problem - this is a big one. opera works on my phone, but even after having advansed gprs connection and connecting the phone to computer with a data cord, it refuses to detect the modem - so can't connect to internet wit this.
    also it is giving problems in accepting the data card.
    btw, battery life has improved like anything.
    give a solution on this headset and moden problem...
    thanks,

  • FTP Connections

    I'm connecting to an ip via ftp, but at certain times the connection gets closed. This causes the program to hang. Is there away to create a timeout just in case the connection has problems. This is a big issue b/c control is never returned to the program.

    I have two sollutions for you:
    1.) Create a guard threat that INTERRUPTS your connection-making thread after a time period
    2.) Create a separate thread that does the connection. Use Object.wait(long timeout) and Object.notifyAll() communication between master thread and connection thread. This will make the master wakeup after your specified period of time with the connection thread still active, but who cares ;-).
    I prefer the second sollution as it doesn't depend on the intteruptability of a connect (I don't know if interrupting a connect is working).
    If you have trouble with established hanging connections, you can set a Socket.setSoTimeOut(int timeout) and get java.io.InterruptedIOExceptions after the timeout exceeds.

  • Scheduler doubts....

    Hi there,
    (1) If there is a job scheduled to run for every 15 minutes (10gr2) and the time for the job tobe complete is 15 minutes only than for whatever reasons, the job takes more than that?Will the second job which is scheduled to run in the next 15 minutes will start even when the before is not yet finished clashing with the previous or it will not start?
    (2)Can we run threads of a job on a grouped data?I mean the requirement which one code is fulfillig is that there are alot of objects.Instead of calculating stats on all at one go,it is dividng them into small groups and running the command dbms_stats on individual groups by making threads using programming.Is there any way that with a single job invoked, multiple threads of thatjob can be started on these number of groups doing the same thing?
    Thanks
    Cheers
    Aman....

    Hi,
    ...responses as I know
    (1) If there is a job scheduled to run for every 15
    minutes (10gr2) and the time for the job tobe
    complete is 15 minutes only than for whatever
    reasons, the job takes more than that?Will the
    second job which is scheduled to run in the next 15
    minutes will start even when the before is not yet
    finished clashing with the previous or it will not
    start?It won't start until previous finished, jobs are queued.
    2)Can we run threads of a job on a grouped data?I
    mean the requirement which one code is fulfillig is
    that there are alot of objects.Instead of calculating
    stats on all at one go,it is dividng them into small
    groups and running the command dbms_stats on
    individual groups by making threads using
    programming.Is there any way that with a single job
    invoked, multiple threads of thatjob can be started
    on these number of groups doing the same thing?You may do that, but must be careful because can take IO levels to the roof, I mean don't recomended for production hours and there is a point of diminishing returns, that is there is an optimal number of threads running, past that point even the stats generation performance will suffer.
    Regards

  • Creaky MuVo battery pack? Also, warmness after uploading files (renamed thre

    Sorry to keep making threads about little things, but I reckon it's worth checking. My MuVo feels quite a bit hotter after I upload files to it (completely fill over USB2.0 usually). It cools down in a few minutes, but I thought I'd check to see if it's normal behaviour. If it's relevant, the USB connector on the main bit (with the controls) is squint (angled towards the screen face of the player).
    Also, my battery module's a bit creaky. When I press buttons on the player or swap the battery I can feel it creaking into different positions. The main player doesn't do this on its own, so I'm wondering if all the battery modules are like that. If not, I might send off for a new battery module as it's only about ?9 and it'd really improve the feel of the player (I hate cheap-feeling plastic if it's something I'm handling a lot).
    Edit- Just to elaborate on the "creaky" thing, the battery pack feels really loose and plasticky on its own and when the main player bit's plugged in. This makes the whole thing feel a bit fiddly, creaking when I press down on buttons or the scroller, when in fact the player bit itself feels solid on its own.
    Now, if I pop the player in the belt clip holster widget, it suddenly "tightens" up, presumably because the holster is pressing in around the player. It feels really, really solid. Is the problem shared by all the battery packs, or have I just mistreated mine a bit's If it's the latter I'll nab a new battery pack.Message Edited by Sockatume on 06-20-2005 03:44 AM

    My Zen Micro heated up a bit when I was charging/transferring files too. I just unplugged it and in a few minutes it was fine. So that seems to be normal. Don't know about the other problem though, sorry.

  • Scripting with beanshell - making a thread solution...

    Ok here is the problem i have and are looking for ideas how to solve it. We have a single threadded server that are using beanshell scripts.
    Now... inside the scripts we want to be able to sleep (wait).
    For example:
    void run(){
        print("test");
        wait(5); // wait 5 seconds
        print("test2");
    }So what i would basically want is that the script is put into somekind of queue, where it will reside for 5 seconds. And then the server would step through the queue and if 5 seconds has passed it would continue executing...
    Is there any "easy" solution to fix this?

    The only solution i come up with so far is making the script call a "script manager" to do the waiting, and with that add a "callback" method.
    So the script would be like
    run(){
      print("test");
      manager.wait(2, "step2()");
    step2(){
      print("test2");
    }The manager would take care of making sure that the callback method is called at the correct time.

Maybe you are looking for