Wait() in Thread programming

Please look at this method:
synchronized void doWhenCondition() {
while(!condition)
wait();
//Do what needs to be done when condition holds
A question that confuses me is: Suppose that all methods of this class are synchronized, and given that only one thread at a time can be executing any procedure of this class, is it still necessary to place condition waits in while loop?

A question that confuses me is: Suppose that all
methods of this class are synchronized, and given that
only one thread at a time can be executing any
procedure of this class, is it still necessary to
place condition waits in while loop? Even if you can determine that only one thread will be waiting, I would still always put wait() in a loop and use notifyAll() instead of notify(). The reason is that when the code is later modified, the assumption that only one thread will be waiting at one time may not be true, and you'll have a serious and hard-to-find bug in your code!
If you do determine that using notifyAll() is a performance problem, you can change it to notify(), but I would then add a big comment explaining that if the code is modified the notify() may need to be changed to notifyAll().

Similar Messages

  • DBMS_SCHEDULER wait for job/program to finish

    Hello All,
    I've run into a little limitation on my understanding of DBMS_SCHEDULER.
    I have an executable script which does a network scan. My goal is to lauch this from an application, and wait (could be 5 minutes or 2 hours) for the scan to finish before I return the results.
    Where I'm a little confused, is the flow of the entire process works when I want to wait for the program to complete:
    1 - Define a program?
    2 - Apply arguments?
    3 - Apply credentials
    4 - Define a chain?
    Literally, I'm not sure how to tackle this task. I simply wish to launch to job and wait for it to finish before I go retreive the file from the server. This is what I have so far, just bits and pieces.
    Mayeb I simply missed somethign in the docs, and I'm overcomplicate things.
    Thanks in advance to the community for you assistance.
    Jan S.
    BEGIN
      dbms_scheduler.create_program(
        program_name   => 'network_scan',
        program_type   => 'executable',
        number_of_arguments => 5,
        program_action => 'scan_network.py',
        enabled        =>  FALSE);
      dbms_scheduler.define_program_argument('network_scan',1,'x01=1');
      dbms_scheduler.define_program_argument('network_scan',2,'x02=192.168.1.1');
      dbms_scheduler.define_program_argument('network_scan',3,'x03=24');
      dbms_scheduler.define_program_argument('network_scan',4,'x04=D');
      dbms_scheduler.define_program_argument('network_scan',5,'x05=1521-1523,7777'); 
      vJobName := dbms_scheduler.generate_job_name('NET_SCAN_');
      dbms_scheduler.create_job(job_name => vJobName,
                                  job_type => 'EXECUTABLE',
                                  job_action => '/usr/bin/scan_nework.sh',
                                  number_of_arguments => 5,
                                  enabled => FALSE,
                                  auto_drop => FALSE,
                                  comments => 'Network');
    dbms_scheduler.set_attribute(vJobName,'credential_name', 'SUCREDENTIALS');
      dbms_scheduler.run_job(vJobName,FALSE);
      dbms_scheduler.create_chain (
       chain_name            =>  'net_scan_chain',
       rule_set_name         =>  NULL,
       evaluation_interval   =>  NULL,
       comments              =>  NULL);
      dbms_scheduler.define_chain_step('net_scan_chain', 'step1', 'network_scan');
      SELECT additional_info, external_log_id
      INTO   l_additional_info, l_external_log_id
      FROM   (SELECT log_id,
                     additional_info,
                     REGEXP_SUBSTR(additional_info,'job[_0-9]*') AS external_log_id
              FROM   dba_scheduler_job_run_details
              WHERE  job_name = vJobName
              ORDER BY log_id DESC)
      WHERE  ROWNUM = 1;
      DBMS_OUTPUT.put_line('ADDITIONAL_INFO: ' || l_additional_info);
      DBMS_OUTPUT.put_line('EXTERNAL_LOG_ID: ' || l_external_log_id); 
      -- Wait at least 3 second because its distributed
      dbms_lock.sleep(3);
      SELECT job_name, status, error#, additional_info
      FROM dba_scheduler_job_run_details
      WHERE job_name= vJobName;
      dbms_lob.createtemporary(l_clob, FALSE);
      dbms_scheduler.get_file(
        source_file     => l_external_log_id ||'_stdout',
        credential_name => 'ORACLECREDENTIALS',
        file_contents   => l_clob,
        source_host     => NULL);
      DBMS_OUTPUT.put_line('stdout:');
      DBMS_OUTPUT.put_line(l_clob);
    k Scan');

    See Tom's last reply in this AskTom thread. It shows how to use the DBMS_ALERT package to signal you.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5320945700346034393

  • Multi threaded programming

    I am quite new to multi threaded programming.
    The problem I am facing in my code is as follows:
    I can instantiate 1-10 threads from my controller class. For example if my controller class generates 10 threads, 5 threads
    finish the task they are assigned to do(i.e send SMS and Update the Database) and the other 5 threads eventhough send SMS but
    get stuck when they are supposed to update the Database (this is inferred from the logs).
    Due to this problem my controller class remains in a wait state as I am using the join() method and some of the threads never
    join.
    Another interesting observation is that it always happens that the thread numbered 0-5 always get stuck at the exact point
    where database has to be updated and thread number 6-10 complete their task. Same is the case when i instantiate 2 threads, i
    thread completes its task and another thread gets stuck, again at the same point.
    I am using Connection Pooling to connect to the database.
    I am sure that the problem is with the query
    int j=dbObject.execute_pst("UPDATE table SET flag='true' WHERE message IN("+trueFlag+")",con);
    where true flag is a comma seperated string containing some ID's.
    What i cannot understand is why some of the threads (almost 50% of them), work fine with this query and the others get stuck
    (i.e. just wait at this query during runtime)

    The problem must lie in the connection, as the SQL statement is to basic to cause an endless loop inside the DBMS. If you are in doubt, try the setMaxRows() method of the Statement interface, I'm using Sybase and it also limits the number of rows processed in update and delete statements (which I'm pretty sure is buggy, but you can still try it).
    Which DBMS are you using by the way?

  • Thread Programming and Condition.Await

    I'm trying to get better acquainted with threaded programming by building a mock music player. It's not going over so well
    What am I doing wrong in the code snipped below? The snippet below is inside the run() method of the MusicPlayer class.
    It seems that it simply doesn't excute as intended. The behavior I want is:
    - When in Off mode: do nothing
    - When in Playing mode: Wait until song finishes, then remove song from playlist (call PlaySong)
    - When in Pause mode: Wait (pauseTimeOut) milliseconds, and if nothing happens, go to Off mode.
    The thread runs fine, but it seems that it waits forever in whatever state it is in.
    I apologize for the weird if statements..
    while (alive) {
                   System.out.println("State: "+state);
                   switch (state) {
                   case Off:
                        System.out.println("System is off");
                        try { cond.await(); }
                        catch(InterruptedException e) { alive = false; }
                        break;
                   case Paused:
                        boolean stillWaiting=true;
                        System.out.println("Waiting..");
                        try { stillWaiting=cond.await(pauseTimeOut, TimeUnit.MILLISECONDS); }
                        catch(InterruptedException e) { alive = false; }
                        if(stillWaiting) {
                             //Do nothing
                        } else if (state == States.Paused) {
                             state=States.Off;
                        break;
                   case Playing:
                        System.out.println("Playing..");
                        if(playlist == 0) {
                             state = States.Paused;
                        } else {
                             boolean waitingEndSong=true;
                             try { waitingEndSong=cond.await(songTime, TimeUnit.MILLISECONDS); }
                             catch(InterruptedException e) { alive = false; }
                             if(waitingEndSong) {
                                  //Do nothing
                             } else if (state == States.Playing) {
                                  PlaySong();
                             break;
                        try { cond.await(); }
                        catch(InterruptedException e) { alive = false; }
                        break;
                   default:
                        alive = false;
    }

    To get better help sooner, post a SSCCE that clearly demonstrates the problem.
    Use 2 to 4 spaces, not tabs, for indentation. Most members won't take the trouble to read code that is too deeeply indented. I know I don't.
    luck, db

  • Package deployment keeps getting stuck with message 'Waiting for another program'

    Hi, I just started working on SCCM.  We have an Orchestrator runbook which creates a collection and then creates an advertisement for packages and task sequences.  I was able to get a task sequence and a package successfully execute.  When
    creating the advertisement, I set it to RERUN_ALWAYS.  However, the next time I ran our runbook which creates the collection andadvertisement (I manually deleted the previous one), it does create them but the deployment is stuck to In Progres with the
    Description of 'Waiting for another program'.  This just happens for packages before and not for task sequences the other day but now, it's the same issue whether I use a package or a task sequence.   
    I see this in execmgr.log:
    <![LOG[Package UAT0007D, program Test is ready but can not be started because package , program  is currently running.]LOG]!><time="17:07:20.993+480" date="02-06-2015" component="execmgr" context=""
    type="1" thread="6804" file="executionrequest.cpp:9083">
    <![LOG[Raising event:
    [SMS_CodePage(437), SMS_LocaleID(1033)]
    instance of SoftDistProgramWaitingForAnotherProgram
    AdvertisementId = "UAT2011A";
    BlockingPackageID = "";
    BlockingProgramName = "";
    ClientID = "GUID:2FE27567-3215-4015-BE09-0E65F09767C8";
    DateTime = "20150207010721.004000+000";
    MachineName = "ACAA-UAT-SCCM";
    PackageName = "UAT0007D";
    ProcessID = 6316;
    ProgramName = "Test";
    SiteCode = "UAT";
    ThreadID = 6804;
    ]LOG]!><time="17:07:21.010+480" date="02-06-2015" component="execmgr" context="" type="1" thread="6804" file="event.cpp:729">
    <![LOG[Successfully raised SoftDistProgramWaitingForAnotherProgram event for program Test.]LOG]!><time="17:07:21.021+480" date="02-06-2015" component="execmgr" context="" type="1" thread="6804"
    file="executionrequest.cpp:9128">

    yes check the exemgr.log file and also see is that package has dependency for another package? and if yes then that package is already available non DP?
    Sharad Singh | My blogs: SharadTech | Twitter:
    @SinghSharaad | | Please remember to click “Mark as Answer” on the post that helps you.This can be beneficial to other community members reading the thread.

  • Running a Java Multi Thread Program in database

    I have created a multi threaded program in Java and it runs successfully from the command prompt. I want to create a DBMS Job which will wake up at regular intervals and runs the java program(Java stored procedure). Is this possible in 9.2/10G ?? If Yes, will there be any impact on the DB performance/increase memory etc.,
    The database (9.2...) resides on a RH 2.3 AS box.
    Any ideas...
    Thanks,
    Purush

    Purush,
    Java stored procedures cannot be multi-threaded. Well, they can, but the threads will not run in parallel. You may be able to find some more information in the Oracle documentation, which is available from:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • Media Recovery Waiting for thread 1 sequence (in transit)

    I have rebuilt our standby database using an rman duplicate since it was missing many archive logs.
    Following the duplicate, the standby is now almost in sync with the primary. Logs are shipping across but are not being applied in a timely manner. How long should it take for an archive log from the primary to be applied to the standby?
    I need to know this so that a proper script can be set up to check the primary and standby. At the moment they are never exactly in sync - always one sequence number behind the primary.
    Why is the standby is not applying in a timely manner?
    From the alert log:
    Media Recovery Waiting for thread 1 sequence 11278 (in transit)
    The log seems to be "in transit" for a long time
    PRIMARY:
    SQL> select max (sequence#) current_seq from v$log;
    CURRENT_SEQ
    11278
    SB:
    SQL> select MAX (SEQUENCE#), APPLIED FROM V$ARCHIVED_LOG where APPLIED ='YES' GROUP BY APPLIED;
    MAX(SEQUENCE#) APP
    11277 YES
    ALERT LOG:
    RFS[2]: Archived Log: '/backup/prod/log_1_11277_704816194.dbf'
    Primary database is in MAXIMUM PERFORMANCE mode
    Mon Nov 1 15:22:01 2010
    Media Recovery Log /backup/prod/log_1_11272_704816194.dbf
    Mon Nov 1 15:26:49 2010
    Media Recovery Log /backup/prod/log_1_11273_704816194.dbf
    Mon Nov 1 15:29:54 2010
    Media Recovery Log /backup/prod/log_1_11274_704816194.dbf
    Mon Nov 1 15:34:18 2010
    Media Recovery Log /backup/prod/log_1_11275_704816194.dbf
    Mon Nov 1 15:36:42 2010
    Media Recovery Log /backup/prod/log_1_11276_704816194.dbf
    Mon Nov 1 15:39:43 2010
    Media Recovery Log /backup/prod/log_1_11277_704816194.dbf
    Mon Nov 1 15:42:34 2010
    Media Recovery Waiting for thread 1 sequence 11278 (in transit)
    I should add that I understand that for the Primary and Standby to be out by one log is not cause for concern (they are applying). Its just that I wanted to script a check that would compare them both, and and the moment they are never equal - when I understand that they should be and that the logs should be applied almost immediately.
    Edited by: Dan A on Nov 1, 2010 4:36 PM

    How long should it take for an archive log from the primary to be applied to the standby?depends on network speed also.
    make sure the archives are shipped to standby location.
    PRIMARY:
    SQL> select max (sequence#) current_seq from v$log;
    CURRENT_SEQ
    11278(this is log not archivelog ) ..... :)SB:
    SQL> select MAX (SEQUENCE#), APPLIED FROM V$ARCHIVED_LOG where APPLIED ='YES' GROUP BY APPLIED;
    MAX(SEQUENCE#) APP
    11277 YES
    Hi check is MRP started or not?
    primary database you need not check current sequence, check last generated sequence..not current sequence.
    current sequence is redo log which has been not yet archived
    I think everything is perfect here.. no issues.
    Hope you understood, let me know if not clear , thanks.

  • Thread programming -  variable might not have been initialized

    Hi there,
    Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
    ThreadController.java:42: variable dataGeneratorThread might not have been initialized
    dataGeneratorThread.activeCount();
    The bit I dont understand is that I run
    this line here
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    but when I do
    dataGeneratorThread.activeCount()
    is balks.
    I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
    Here is some of the code
    runable class{
    new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
    public class ThreadController implements Runnable {
    DataBuffer inputBuffer;
    DataBuffer displayBuffer;
    JuliaCalc juliaCalc;
    /** Creates a new instance of ThreadController */
    public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
    inputBuffer = inputBuffer;
    displayBuffer = displayBuffer;
    juliaCalc = juliaCalc;
    public void run()
    DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
         WorkerThread dataGeneratorThread;
         for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators[i],juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    dataGeneratorThread.activeCount();
    int nNanoSecsBeforeCheck = 50;
    while(true)
    if(dataGeneratorThread.isAlive()){
    if(dataGeneratorThread.activeCount() > inputBuffer.size())
    public class DataGenerator implements Runnable {
    int nImageWidth;
    int nImageHeight;
    DataBuffer inputBuffer;
    public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
    nImageWidth = ImageWidth;
    nImageHeight = ImageHeight;
    public void run()
    // Non terminating thread - created datapakets and place them in the input buffer
    // Get two radom number withoin a bound and find out bout default highest colou - 3rd value
    while(true)
    int nRandomXCord;
    int nRandomYCord;
    nRandomXCord = ((int)(Math.random() * nImageWidth));
    nRandomYCord = ((int)(Math.random() * nImageHeight));
    DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
    inputBuffer.put(dpDataPacket);

    Sorry about that, didnt realise.
    Hi there,
    Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
    ThreadController.java:42: variable dataGeneratorThread might not have been initialized
    The bit I dont understand is that I run
    this line here
    this line here
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    }but when I do
    dataGeneratorThread.activeCount() is balks.
    I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
    Here is some of the code
    runable class{
    new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
    public class ThreadController implements Runnable {
    DataBuffer inputBuffer;
    DataBuffer displayBuffer;
    JuliaCalc juliaCalc;
    /** Creates a new instance of ThreadController */
    public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
    inputBuffer = inputBuffer;
    displayBuffer = displayBuffer;
    juliaCalc = juliaCalc;
    public void run()
    DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
    WorkerThread dataGeneratorThread;
    for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
    dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
    dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
    dataGeneratorThread.start();
    dataGeneratorThread.activeCount();
    int nNanoSecsBeforeCheck = 50;
    while(true)
    if(dataGeneratorThread.isAlive()){
    if(dataGeneratorThread.activeCount() > inputBuffer.size())
    public class DataGenerator implements Runnable {
    int nImageWidth;
    int nImageHeight;
    DataBuffer inputBuffer;
    public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
    nImageWidth = ImageWidth;
    nImageHeight = ImageHeight;
    public void run()
    // Non terminating thread - created datapakets and place them in the input buffer
    // Get two radom number withoin a bound and find out bout default highest colou - 3rd value
    while(true)
    int nRandomXCord;
    int nRandomYCord;
    nRandomXCord = ((int)(Math.random() * nImageWidth));
    nRandomYCord = ((int)(Math.random() * nImageHeight));
    DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
    inputBuffer.put(dpDataPacket);
    }

  • Using nanosleep() in a threaded program cause SIGBUS or SIGSEGV

    Greetings,
    I'm working on a multit-threaded program using Solaris' threads (not POSIX).
    When I call nanosleep() or usleep(), sometimes the program works well, but often I get either a SIGSEGV or a SIGBUS.
    Have a look at the following dbx output using a core file:
    (dbx) threads
    o>    t@1  a  l@1   ?()   signal SIGSEGV in  t_splay()
          t@2  a  l@2   cpu_thread()   LWP suspended in  ___nanosleep()
    (dbx) thread 2
    dbx: unrecognized arg/option '2'
    Use the 'help' command for more information.
    (dbx) thread t@2
    Current function is cpu_thread
      367           nanosleep(&sleep_time, NULL);
    t@2 (l@2) stopped in ___nanosleep at 0xfe5c017c
    0xfe5c017c: ___nanosleep+0x0008:        bcc,a,pt  %icc,___nanosleep+0x18       ! 0xfe5c018c
    (dbx) list
      367           nanosleep(&sleep_time, NULL);
    (dbx)The code used to create the thread:
    thr_create(NULL, 0, cpu_thread, NULL, 0, &tid);Am I missing something?
    Any suggestions are welcome.
    Thanks,
    -Thomas

    t@1 a l@1 ?() signal SIGSEGV in t_splay() Most likely a corrupted malloc heap. Thread t@1 is crashing
    somewhere inside malloc() or free().
    Use libumem(3LIB) or dbx's access / memory checking support
    to find out where you're corrupting the malloc heap.
    t@2 a l@2 cpu_thread() LWP suspended in ___nanosleep() The nanosleeping thread isn't responsible for the crash.
    The t@1 thread is the culprit. Print a stack trace for thread t@1.

  • Thread program: Strange output

    Hi,
    I have written a simple thread program. Previously I was trying to print hello world in the run method, the I changed it to print the value of a static data member, but strangely its still printing hello World. However if I change the print statement in the main method, it is reflected in the output but the changes to the print statement are not. Its always hello World output. I have changed the name of file, recompile it, close the shell window, restarted the computer but always the output is hello world. Can somebody help me with that. My objetive is to prove that data segment is shred in threads.
    public class Share2 extends Thread{
    static int Data=10;
       public void run ( ) {
        Data=Data+10;
         System.out.println("Data="+Data);
      public static void main (String[ ] args ) {
        First obj=new First ( );
        obj.start ( );
        System.out.println("Data ^^^^in!!! 9999main****="+Data);
    }D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>
    Zulfi.

    public class Share2 extends Thread{
    static int Data=10;
    public void run ( ) {
    Data=Data+10;
    System.out.println("Data="+Data);
    public static void main (String[ ] args ) {
    First obj=new First ( );<<<<< what is First? >>>>>>
    obj.start ( );
    System.out.println("Data ^^^^in!!!
    n!!! 9999main****="+Data);
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>javac Share2.java
    D:\javaprogs\misc\threads>java Share2
    Data ^^^^in!!! 9999main****=10
    Hello World
    D:\javaprogs\misc\threads>
    Zulfi.

  • Update of jlabel does not happen when i wait for thread to finish (join())

    gurus please help.
    I have a main application which in actionevent calls a thread, that thread calls parent method to update ths status in jlabel, but when i use thread.join() to wait for process to complete, the jlabel does not get updated, please tell me how can i update the jlabel, i have to wait for thread to finish and during run i need to update the jlabel.
    thanks

    hi camickr and gurus:
    here is the code:
    notice after pressing the Process button, the label is being updated but its not working. I called the processnow() method directly and also by thread, but in thread I have to wait until it finishes using join() but still does not work, please help. Thanks
    package label;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class thePanel extends JDialog {
      private DefaultTableModel tableModel = null;
      private JTable theTable = new JTable();
      private JScrollPane scrollPane = new JScrollPane();
    JPanel tPanel = new JPanel();
      private Border mainBorder;
      private BorderLayout borderLayout1 = new BorderLayout();
      private BorderLayout borderLayout2 = new BorderLayout();
      private BorderLayout borderLayout3 = new BorderLayout();
      private BorderLayout borderLayout4 = new BorderLayout();
      private JPanel statusPanel = new JPanel();
      private JPanel buttonPanel = new JPanel();
      private JPanel lowerPanel = new JPanel();
      private JLabel statusBar = new JLabel();
      private JButton processButton = new JButton("Process");
      public JButton closeButton = new JButton("Close");
      boolean image = true;
      theProcess processThread;
      Vector tableData = new Vector();
      ImageIcon Image = new ImageIcon("image.gif");
      ImageIcon oImage= new ImageIcon("oimage.gif");
      boolean errorOcurred=false;
      String statusMessage;
      public thePanel() {
        try {
         jbInit();
        } catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        tPanel.setPreferredSize(new Dimension(800,424));
        mainBorder = new TitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)," ");
        statusPanel.setBorder(BorderFactory.createEtchedBorder());
        tPanel.setBorder(mainBorder);
        tPanel.setLayout(borderLayout1);
        scrollPane.getViewport().add(theTable, null);
        tPanel.add(scrollPane,  BorderLayout.CENTER);
        // status
        statusPanel.setLayout(borderLayout2);
        statusPanel.setBorder(BorderFactory.createEmptyBorder());
        statusBar.setAlignmentX((float) 0.5);
        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
        statusBar.setMaximumSize(new Dimension(600, 21));
        statusBar.setMinimumSize(new Dimension(600, 21));
        statusBar.setPreferredSize(new Dimension(600, 21));
        statusPanel.add(statusBar, BorderLayout.SOUTH);
        // buttons
        processButton.setPreferredSize(new Dimension(70,25));
        processButton.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            process_actionPerformed(e);
        closeButton.setPreferredSize(new Dimension(70,25));
        buttonPanel.setLayout(borderLayout3);
        buttonPanel.setBorder(BorderFactory.createRaisedBevelBorder());
        buttonPanel.add(processButton,BorderLayout.WEST);
        buttonPanel.add(new JPanel());
        buttonPanel.add(closeButton,BorderLayout.EAST);
        // lower panel
        lowerPanel.setLayout(borderLayout4);
        lowerPanel.setBorder(BorderFactory.createEmptyBorder());
        lowerPanel.add(statusPanel, BorderLayout.WEST);
        lowerPanel.add(buttonPanel, BorderLayout.EAST);
        tPanel.add(lowerPanel, BorderLayout.SOUTH);
        theTable.setAutoCreateColumnsFromModel(true);
        theTable.setColumnSelectionAllowed(false);
        theTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        theTable.getTableHeader().setReorderingAllowed(false);
    getContentPane().add(tPanel);pack();
        getinfo();
    show();
      private void prepairTable(){
        tableModel = new DefaultTableModel(){
                          public boolean isCellEditable(int row, int col)
                            { return false; }};
        tableModel.addColumn("text 1");
        tableModel.addColumn("text 2");
        tableModel.addColumn("text 3");
        tableModel.addColumn("text 4");
        tableModel.addColumn("text 5");
        theTable.setModel(tableModel);
      } // end method (prepairTable)
      public void refreshTable() {
        prepairTable();
      public void getinfo() {
        try {
            refreshTable();
            tableModel.addRow(new Object[]{"3465465555","0123456789",new Date(1135022905196L),"0100000","errror message","sssssss"});
            tableModel.addRow(new Object[]{"8949344562","0324354549",new Date(1134511763683L),"0166600","errror mes666e","ddddddd"});
    setStatusMessage("ready to process, select record and click Process button to process record");
          errorOcurred = false;
        } catch (Exception ex) {
          errorOcurred = true;
          ex.printStackTrace();
        } // End try
      private void process_actionPerformed(ActionEvent e) {
        try {
          if(theTable.getSelectedRows().length > 0) {
    //        processThread = null;
    //        processThread = new theProcess(this);
    //        processThread.start();
    processnow();
            System.out.println("........finished now.........");
          } else {
        } catch (Exception ex) {
          ex.printStackTrace();
      public void processnow() {
        try {
          int[] selectedRows = null;
          int totalSelected = 0;
          setStatusMessage("processing " + totalSelected + " selected records...");Thread.sleep(1500);
          selectedRows = theTable.getSelectedRows();
          totalSelected = selectedRows.length;
          for(int i = 0; i < totalSelected ; i++){
            setStatusMessage("processing " + (i+1) + " of " + totalSelected + " selected records...");
            System.out.println(".......................row: "+selectedRows);
    Thread.sleep(2500);
    System.out.println("........fins...........");
    errorOcurred = false;
    } catch (Exception ex) {
    errorOcurred = true;
    ex.printStackTrace();
    } // End try
    public void setStatusMessage(String message) {
    statusMessage=message;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    if(image)
    statusBar.setIcon(Image);
    else
    statusBar.setIcon(oImage);
    statusBar.setText(statusMessage);
    statusBar.update(statusBar.getGraphics());
    public static void main(String[] args){
    new thePanel();
    } // class
    package label;
    import java.lang.Runnable;
    public class theProcess implements Runnable {
    private thePanel parent;
    public theProcess(thePanel xparent){
    parent = xparent;
    } // end constructor
    public void start() {
    try {
    Thread thisThread = new Thread(this);
    thisThread.start();
    thisThread.join();
    } catch(Exception ex) {
    ex.printStackTrace();
    } // end method (start)
    public void run(){
    try {
    parent.processnow();
    } catch (Exception ex){
    ex.printStackTrace();
    } // end try
    } // end method (run)
    } // end class

  • Need help with java thread program

    Hi
    I have an applet which does some painting etc, i need to write a thread which runs in background, and if there is no user activity for 30 min will refresh the screen.
    I have one good thing that all user options go from one program so i know when user does some thing.
    How do i write this thread program?
    1. I need this program to start counter as soon as some activity is done by user
    2. When user does some thing stop this thread
    3. when user completes his action restart the thread with 30 min timer.
    4. when there is no activity for 30 min refresh the screen
    Any help will be really good
    Ashish

    Not sure what the problem is. Your pseudo code looks good to me.
    The only suggestion I would make is that your use a Timer so you don't have to worry about creating your own Thread. You schedule a Timer to fire in 30 minutes. Everytime you have activiity you cancel the timer and reschedule it.

  • Single Threaded Program

    What do you mean by a single threaded program?? For example I have a single threaded word processor which can do only one task at a time. Does this mean that there is one and only thread which is carrying out all tasks one at a time??Say,formatting the document and then printing??I think I'm very near to it but not getting it properly.Please help.Thanks a lot.

    A single threaded program is a normal program that has only one thread. That doesn't mean that it can do only one task at a time, but that one thread is performing all the tasks.

  • HELP!....GUI crashes when i call a multi-threaded program from it

    Hi..I have encountered a problem in my end of year project, which i cant see to solve. The problem is i am starting a multi-threaded program for a JButton on a GUI. All though this starts the other program it crashes the GUI completely how do i stop this.
    this is the code i use to call the threaded program.
    public void actionPerformed(ActionEvent e)
    Object target=e.getSource();
    String line = new String();
    if( target==b1 )
         try
    cl = new client();
         cl.startup();
         catch(Exception ex){ex.printStackTrace();}
    thanks Mike

    No there is no exceptions being given. this is one of the reasons why i dont no what to do. i thought myself that the threaded was taking all the resources and not going back to the GUI. if this is the case is there anyway that i can call back the GUI and keep the threaded program running?
    thanks
    mike.

  • Paul Hyde's Java Thread Programming

    I have Paul Hyde's Java Thread Programming and I am wondering if it is a comprehensive book for learning the nuts n bolts of threads. I know how to use threads however I want to learn the inner details. Doug Lea's book is perhaps a better option but Paul Hyde's book seems more readiable.
    Any comments are appreciated.
    cheers

    Sounded interesting, found this link
    http://www.javaspecialists.co.za/archive/Issue056.html

Maybe you are looking for

  • By time machine can i repair my MacBook Air?

    I have the late 2012 Macbook air and my battery does not go up to 100% it is stuck at the 90's so just asking if i back up my data with Time machine go in the apple DOS mode will that fix it also is it ok to leave the battary on the charger and can i

  • When I plug my iphone in to my computer I get a message that "a usp device is not recognized"

    When I plug my iphone in to my computer I get a message that "a usp device is not recognized" I fear resetting my phone when I haven't had a chance to back it up in itunes.  I cannot connect to my computer thru wifi either.

  • Help needed regarding to nokia x2

    hi sir i gotta nokia x2 firm ware 4.80 sir i captured ma graduation pics in it on 1st nov bt unfortunately al photos which i took on 31st october nd 1st novmber got erased automaticaly,now today as i chkd the foldr ov pics the fotos were thr bt they

  • Exec.State and Start Asynchrono​us Call

    In my application I like to start a VI asynchronously by pressing a button control. I just want to have one instance of the VI running so I let the caller test if the VI is already running. Unfortunately there seems to be a bug in the Exec.State prop

  • Uninstalled Bonjour, now startup error message.

    I have just set up a network using an Airport Extreme router. The users on the network all use Windows XP. The printer connected to the Airport is an HP 3050 AIO. Bonjour would see the printer but would not send print jobs. SWet the printer connectio