Thread resume
cant resume the thread after thread wait is called
plz help
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class numbers {
filee p=new filee();
Thread t=new Thread(new sclass());
public static void main(String []args){
numbers n=new numbers();
n.all();
n.resume();
public void all(){
t.start();
public void resume(){
String input=JOptionPane.showInputDialog(null, "Enter 1 to resume");
if(input.equals("1")){
p.resume();
class sclass implements Runnable{
filee f=new filee();
public void run(){
f.printnum();
class filee{
int i;
public synchronized void printnum(){
for(i=0;i<100;i++){
System.out.print(i);
if(i==50){
try{
Thread.sleep(4000);
}catch(Exception e){
if(i==60){
try{
wait();
}catch(Exception e){
System.out.println(e);
public synchronized void resume(){
notifyAll();
}
The wait()-method doesn't work like that.
Read the tutorial, or maybe the full tutorials about that.
Edit: I now see you're not invoking the (deprecated) resume-method on Thread, but on a Filee-object. The problem is that you have to invoke notifyAll() on the SAME object as you invoked wait() on, and you obviously don't do that.
Edited by: Peter_vd_Wal on 30-mei-2009 11:21
Similar Messages
-
Thread.suspend and Thread.resume
I'm trying to build a class to replace the use of Thread.suspend() and Thread.resume() deprecated methods.
I tried to as recommended on sun web page but it doesn't work : illegate state monitor exception.
Does anyone have a solution ?
Note :
Source code
package com.utils;
public class SuspendableThread extends Thread {
private Object mutex = new Object() ;
private volatile boolean suspended = false ;
private Runnable runnable ;
public SuspendableThread ( Runnable runnable )
super(runnable) ;
this.runnable = runnable ;
* Suspend the current thread
public void doSuspend()
synchronized (mutex) {
suspended = true ;
while(suspended) {
try {
runnable.wait() ;
} catch (InterruptedException e) {
e.printStackTrace();
* Resume the current thread if suspended
public void doResume()
synchronized (mutex) {
if (suspended) {
suspended = false ;
runnable.notify() ;
Exception
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at com.utils.SuspendableThread.doSuspend(SuspendableThread.java:39)If you're synchronizing on the mutex, you should wait() and notify() on the mutex.
synchronized (mutex) {
suspended = true ;
while(suspended) {
try {
mutex.wait(); //wait on the mutex
} catch (InterruptedException e) {
e.printStackTrace();
synchronized (mutex) {
if (suspended) {
suspended = false ;
mutex.notify(); //notify threads waiting on the mutex
//... -
Error thread java : problem with the function "resume 0x***" (forum sun)
One problem with the function of jdb occured when I tried to use it to
pilot the processor with differents threads. In fact, I use a simple example with 2 threads.
I stop the two threads with two breakpoint, and I want to resume one or the other (with the function "resume 0x****"), the one wich I resumed stop again on the breackpoint and I decide again to resume one or the other. All of that to obtain a tree of execution.
I give you the code of the class and the code of jdb.
CLASS: (it's just a object Room with a variable degre that I increment and decrement with two threads increase and decrease)
public class Test{
public static void main(String[] args){
Room r = new Room();
decrease de = new decrease(r);
increase in = new increase(r);
de.start();
in.start();
class Room {
private volatile int degre=20;
public void more(){
degre += 4;
public void less(){
degre -= 3;
class decrease extends Thread{
private Room room;
public decrease(Room r){
room =r;
public void run(){
try{
while (!interrupted()){
room.less();
catch(InterruptedException e) {}
class increase extends Thread{
private Room room;
public increase(Room r){
room =r;
public void run(){
try{
while (!interrupted()){
room.more();
catch(InterruptedException e) {}
JDB:
Initializing jdb ...
stop at Test:7Deferring breakpoint Test:7.
It will be set after the class is loaded.
runrun Test
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Test:7
Breakpoint hit: "thread=main", Test.main(), line=7 bci=30
7 in.start();
main[1] stop at room:16
Set breakpoint room:16
main[1] stop at room:20
Set breakpoint room:20
main[1] resume
All threads resumed.
>
Breakpoint hit: "thread=Thread-0", room.less(), line=20 bci=0
20 degre -= 3;
Thread-0[1] threads
Group system:
(java.lang.ref.Reference$ReferenceHandler)0x10d Reference Handler cond. waiting
(java.lang.ref.Finalizer$FinalizerThread)0x10c Finalizer cond. waiting
(java.lang.Thread)0x10b Signal Dispatcher running
Group main:
(decrease)0x146 Thread-0 running (at breakpoint)
(increase)0x147 Thread-1 running (at breakpoint)
(java.lang.Thread)0x148 DestroyJavaVM running
Thread-0[1] resume 0x147
Thread-0[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] resume 0x147
Thread-1[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] print degre
degre = 24
Thread-1[1] resume 0x146 //It's here the problem, thread 0x146 have to stop on the //next breakpoint of decrease but nothing happen
Thread-1[1] resume 0x147
Thread-1[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] clear
Breakpoints set:
breakpoint Test:7
breakpoint room:16
breakpoint room:20
PS: I tried many other examples with other class and other kind of breakpoints, but, in any cases, on thread doesn't manage to resume. When I try with general resume (no specification of the thread), It works but it isn't interresting for me because I want to decide wich thread continue his execution.Hi,
I have read the FAQ of the JMF.
The problem was the jar files of the JMF were not in the JRE\BIN\EXT
folder of the Java runtime!
now it works!
thanks
Reg -
Can't kill a running thread...
I'm having some problems killing a thread. Becuase thread.stop() is no longer used, I basically set a flag to tell all the threads to return by checking this flag in the run() method. The problem now is that there is a thread that is getting "stuck" in a class that I have no access to. So basically I assume that its a really long loop, or an infinite loop... either way, that thread doesn't stop even if the "parent" (spawning) thread is "stopped". Any suggestions?
-LJava's Thread Tutorial
JavaWorld: Introduction to Java threads
IBM: Introduction to Java threads
Google: java+threads+tutorial
Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? -
Problem when using swings with thread
Hi,
I am trying to read a database randomly and printing it in a jframe(using jtable and jscrollpane). I am continously checking the values in the database using a infinite do .. while .. loop. and printing the values in the JFrame. I am also making the main thread sleep for every 5 seconds. but when the thread resumes from sleep the JFrame gets the focus. This disturbs me a lot, because of this i am not able to use any other programs like (outlook or word). Kindly provide me a way to continously check the database and print values in the JFrame in the background without JFrame gaining the focus until i click on it.
Regards
KishdudeIt's not clear where you actually tell the JFrame to display itself (usually setVisible(true).
But this is a bit confused.
If the first loop is, in fact, infinite then the table will never be created, since the rest of the code won't be reached.
Don't create a new JTable each time you update the data. Update the existing one. You should define a method, somewhere, to load the table data from the database, call it once while building the window to load the initial values and then - once the window is displayed, set a loop or a Timer going to rescan the data periodically using the same code.
There are serveral ways you can manage the table data. The key is the TableModel associated with the table. You can change the content of the TableModel or create a new one each time you read the data and use JTable's setModel method to replace it. Personally I'd write a subclass of AbstractTableModel or perhaps DefaultTableModel and put the code to scan the database, plus the data read, in there.
There's not a lot of point in making the main thread wait once you've openned a window. The program won't exit while it has a window open. You can call setDefaultCloseAction() on the window and tell it to close the program when the close button is clicked. Or you can add a WindowAdapter to the window and deal with the close attempt yourself.
And don't throw away exceptions in cache clause like you are, because you're never going to debug successfully if you do that. At the very least call printStackTrace() on the exception.
So your sequence should be (roughly)
Load the first batch of data into a TableModel.
Build the window, using the TableModel to create your table.
display the window.
Start a background Thread which repeatedly waits a few seconds, then rereads the data into the table model, ensuring it calls the fireTableModelChanged() method of the model that requests that the table be redrawn. -
Bug with function "resume 0x****" of jdb
One problem with the function of jdb occured when I tried to use it to
pilot the processor with differents threads. In fact, I use a simple example with 2 threads.
I stop the two threads with two breakpoint, and I want to resume one or the other (with the function "resume 0x****"), the one wich I resumed stop again on the breackpoint and I decide again to resume one or the other. All of that to obtain a tree of execution.
I give you the code of the class and the code of jdb.
CLASS: (it's just a object Room with a variable degre that I increment and decrement with two threads increase and decrease)
public class Test{
public static void main(String[] args){
Room r = new Room();
decrease de = new decrease(r);
increase in = new increase(r);
de.start();
in.start();
class Room {
private volatile int degre=20;
public void more(){
degre += 4;
public void less(){
degre -= 3;
class decrease extends Thread{
private Room room;
public decrease(Room r){
room =r;
public void run(){
try{
while (!interrupted()){
room.less();
catch(InterruptedException e) {}
class increase extends Thread{
private Room room;
public increase(Room r){
room =r;
public void run(){
try{
while (!interrupted()){
room.more();
catch(InterruptedException e) {}
JDB:
Initializing jdb ...
stop at Test:7Deferring breakpoint Test:7.
It will be set after the class is loaded.
runrun Test
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Test:7
Breakpoint hit: "thread=main", Test.main(), line=7 bci=30
7 in.start();
main[1] stop at room:16
Set breakpoint room:16
main[1] stop at room:20
Set breakpoint room:20
main[1] resume
All threads resumed.
>
Breakpoint hit: "thread=Thread-0", room.less(), line=20 bci=0
20 degre -= 3;
Thread-0[1] threads
Group system:
(java.lang.ref.Reference$ReferenceHandler)0x10d Reference Handler cond. waiting
(java.lang.ref.Finalizer$FinalizerThread)0x10c Finalizer cond. waiting
(java.lang.Thread)0x10b Signal Dispatcher running
Group main:
(decrease)0x146 Thread-0 running (at breakpoint)
(increase)0x147 Thread-1 running (at breakpoint)
(java.lang.Thread)0x148 DestroyJavaVM running
Thread-0[1] resume 0x147
Thread-0[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] resume 0x147
Thread-1[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] print degre
degre = 24
Thread-1[1] resume 0x146 //It's here the problem, thread 0x146 have to stop on the //next breakpoint of decrease but nothing happen
Thread-1[1] resume 0x147
Thread-1[1]
Breakpoint hit: "thread=Thread-1", room.more(), line=16 bci=0
16 degre += 4;
Thread-1[1] clear
Breakpoints set:
breakpoint Test:7
breakpoint room:16
breakpoint room:20
PS: I tried many other examples with other class and other kind of breakpoints, but, in any cases, on thread doesn't manage to resume. When I try with general resume (no specification of the thread), It works but it isn't interresting for me because I want to decide wich thread continue his execution.Looks like a memory clearing problem in the function. Best to post this problem in an OSS message, or look through the OSS notes to see if the problem has been identified before.
Michael. -
I am running Class ThreadTestB. I am not able to get the region why
ThreadTestB b1 = new ThreadTestB("b1.......");
ThreadTestB b2 = new ThreadTestB("b2 ****");
Is also executing.
If “b1” will execute Infinite time then lock will not released . so “b2” execution is not possible. But when u run
Class ThreadTest B. B2 execution is also done . Why it is passible ?.
public class ThreadTestB extends Thread {
ThreadTestB(){}
ThreadTestB(String str){
super(str);
//FileOutputStream fout= new FileOut
ThreadTestA a = new ThreadTestA();
public void run()
a.Am1();
a.Am2();
public static void main(String[] args) {
ThreadTestB b1 = new ThreadTestB("b1.......");
ThreadTestB b2 = new ThreadTestB("b2 ****");
b1.start();
b2.start();
public class ThreadTestA {
//FileOutputStream fout= new FileOut
public synchronized void Am1(){
System.out.println(" Am1 start to execute .."+Thread.currentThread().getName());
while(true){
System.out.println(" Am1 ...........00000 current thread "+Thread.currentThread().getName());
// try{Thread.sleep(1000);
// }catch(Exception exp){}
public synchronized void Am2(){
while(true){
System.out.println(" Am2 ***********1111current thread "+Thread.currentThread().getName());
// try{Thread.sleep(1000);
// }catch(Exception exp){}
public static void main(String[] args) {Thank ,
but pls explain by Example. I'm sure the tutorial has examples.
Here are a couple more examples.
http://www.javaalmanac.com/cgi-bin/search/find.pl?words=thread
You might also want to check out Doug Lea's Concurrent Programming in Java
Here's yawmark's list of goodies. I'm sure you'll find examples there too:
Java's Thread Tutorial
JavaWorld: Introduction to Java threads
IBM: Introduction to Java threads
Google: java+threads+tutorial
Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
Go through some of this stuff, and if you have a question more specific than "How do I use threads to handle multiple requests?" then post again.
Oh, also, if you need an intro to the socket side of it:
http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
The Java™ Tutorial - Lesson: All About Sockets
Sockets programming in Java: A tutorial -
KDE login: Fetch Job Error
Hi,
since today I receive an error message when I log in into KDE. It says
"Fetch Job Error - Plasma Desktop Shell
Unknown Error: Unable to fetch from backend"
I have to click OK otherwise I can't use the system. After that everything works (or at least seems to).
Don't know if this is related or belong into another thread: Resume from KDEs Suspend doesn't work anymore - the screen just turns black.
Last edited by Barghest (2011-12-28 11:17:54)This is probably caused by some stale entries in the akonadi cache for your calendars. Try to remove and re-add the calendars in korganizer, that fixed the error for me. This error was silent before, but a "fix" in 4.7.4 makes it show those annoying dialogs.
-
Hi there,
I have met a pretty challenging problem in JMS queue consumer and
would like to know if any JMS lovers in the group know about it.
We have queue receiver listening on queue which contains a number of
mugs.
Once a msg is received (onMessage returns), the msg is handed over to
a worker thread from a thread pool.
Essentially there are two parts of the problem:
1. We want kind of flow control - only x number of msg can be
processed at a given time. This can be resolved by using semaphore.
However, there might be better solution out there. Anyhow, this is
less an issue than the second part -
2. As we know client_acknowledge happens at the session level:
Acknowledging a consumed message automatically acknowledges the
receipt of all messages that have been consumed by its session. For
example, if a message consumer consumes ten messages and then
acknowledges the fifth message delivered, all ten messages are
acknowledged.
-- this is the problem -- we want to acknowledge each msg
individually so that only the processed msg is acknowledged although
there are x number of msg being retrieved. By doing that we won't lost
any msg in case the JMS client crashes.
It is a challenge, isn't it? Might well not be one for you, if you
know the trick. If you do, could you share with us? Thanks a lot.
Mike
Just to be clear, I favor (2), where each worker thread has its own session and
consumer.
This naturally throttles, as there are only as many outstanding messages as
worker-threads.
BTW, be aware that it is against spec, and dangerous, to call acknowledge()
outside of
onMessage() - as this multi-threads the Session and Session's are not thread
safe.
Tom
Tom Barnes wrote:
> Actually you both are correct. The ack behavior is configurable on the
> connection factory via the "AcknowledgePolicy", where the default is
> what the spec requires (ack-all). Prior to 6.1
> the behavior was what one would expect (ack-before).
>
> As for how to solve the problem at hand. I can think of three approaches:
>
> (1) use the current async consumer but set the ack-policy
> to ack-before, and defer acknowledging a msg until all msgs before
> it have finished their processing
>
> (2) use multiple synchronous consumers, one consumer per defered msg
>
> (3) use a single synchronous consumer, but dequeue transactionally,
> one transaction per msg. suspend the transaction, then have
> the worker thread resume the transaction once it finishes processing
> the message and call commit. (Take care that the default
> tran timeout is 30 seconds.)
>
> Shean-Guang Chang wrote:
>
> > Just to correct one assumption. Ack the fifth message will not ack message
> > received after that (e.g. message 6, 7, 8, etc...). At least not WLS JMS.
> > If this is not true for you please give details of your client code and
> > version of WLS JMS you have. Thanks!
> >
> > "Mike" <[email protected]> wrote in message
> > news:[email protected]...
> > > Hi there,
> > >
> > > I have met a pretty challenging problem in JMS queue consumer and
> > > would like to know if any JMS lovers in the group know about it.
> > >
> > > We have queue receiver listening on queue which contains a number of
> > > mugs.
> > > Once a msg is received (onMessage returns), the msg is handed over to
> > > a worker thread from a thread pool.
> > >
> > > Essentially there are two parts of the problem:
> > >
> > > 1. We want kind of flow control - only x number of msg can be
> > > processed at a given time. This can be resolved by using semaphore.
> > > However, there might be better solution out there. Anyhow, this is
> > > less an issue than the second part -
> > >
> > > 2. As we know client_acknowledge happens at the session level:
> > > Acknowledging a consumed message automatically acknowledges the
> > > receipt of all messages that have been consumed by its session. For
> > > example, if a message consumer consumes ten messages and then
> > > acknowledges the fifth message delivered, all ten messages are
> > > acknowledged.
> > > -- this is the problem -- we want to acknowledge each msg
> > > individually so that only the processed msg is acknowledged although
> > > there are x number of msg being retrieved. By doing that we won't lost
> > > any msg in case the JMS client crashes.
> > >
> > > It is a challenge, isn't it? Might well not be one for you, if you
> > > know the trick. If you do, could you share with us? Thanks a lot.
> > >
> > > Mike
-
Hi all,
I am using the Timer class provided with JDK1.4. During scheduling, you take the current time as the reference time for relative timer. Everything is ok if i dont change the system time.
But consider this scenario. If i have a heartbeat timer (which dont worries about the current time) which ticks every 500 milliseconds ( after some 5 to 6 ticks I am disconnecting from the server) but when I change the system time, the heartbeat will tick many number of times depending on the changed time assuming that timout is happened and get disconnected with the server.
How can I solve this? If it can't be done with jdk timer, please help in identifying a solution for this?
TIA
KarthikIn response to cpolizzi: (Not in original posting order)
One reason that I do not like the
javax.swing.Timer is that it requires a
graphical subsystem to be present.One would expect that from a javax.swing class, yes. Swing is a graphical toolkit.
Digressing slightly, note that since Java 1.4, the AWT no longer needs a graphical subsystem to be present, so image manipulation (and such) is now possible on headless J2EE servers.
The Java application created and started both J2SE
supplied timers each for a one minute delay as well as
two other threads. One thread does a
Thread.sleep for one minute and the other
thread does an Object.wait with a timeout for
one minute on a locally created object to synchronize
on. After the two timers and threads were started,
which I tried to start as close as possible, the main
application thread also does a Thread.sleep for
one minute. After the main application thread went to
sleep, I changed the system clock back by one minute.
The results: the two threads doing a
Thread.sleep and Object.wait "woke" back
up after one minute even despite the change in the
system clock as did the main application thread also
doing a Thread.sleep. However, the two J2SE
supplied timers did not. Instead, each of those
timers "expired" when the system clock reached one
minute after the time in which each one was scheduled
or started. I encountered this behavior on both of
the JVM's I have loaded on my W2K box.This is 100% correct behaviour, exactly as I would expect.
I also tried setting the system clock ahead by 30
seconds, one minute and even five minutes after
everything is going and it seems that the J2SE timers
were not affected - each expired right when other
threads resumed from their sleep and wait. I
encountered this behavior on both of the JVM's I have
loaded on my W2K box.Once again, this behaviour is as close to correct as is reasonably possible.
Without delving into the implementation into either
one of the J2SE supplied timers, it seems to me that
both of these timers, when they are effectively
started ticking, calculate the expected expiration
time relative to the current system time and use a
polling mechanism on seperate threads.Perhaps you should have delved.
java.util.Timer works on a priority queue of tasks. It will wait (using Object.wait()) for the time period required for the next task to expire, and then test if the task has indeed expired, through a comparison to System.currentTimeMillis(). If it hasn't, presumably because of spurious wakeup, it will again wait until it expects the task to expire and retest. Exceptions to this flow may occur if the task queue changes - if a task is scheduled or rescheduled, so the expected closest expiry time is closer than the current waiting time, then the wait will be interrupted and recalculated. If the next task is unscheduled, then the wait will be interrupted and recalculated for the next task in line.
Thus, if you move the system time back, then the timer will indeed wait until the Task's scheduled expiry date/time has been reached... if you move the system time forward, then when the timer wakes up from its wait, it will realise that the task has indeed expired and it will fire as expected, unless it is deemed too late to fire.
To summarise, java.util.Timer is an optimal implementation of a single-threaded event scheduler for events scheduled to execute at a particular time in the future, marked by a given date and time. See below for comments on spurious wakeup for why this is so.
My bottom line expectation is that when it comes to
relative timers, a duration is a duration regardless
of what happens to the system's notion of current
time.You will note that java.util.Timer offers a cron-like facility for tasks to be performed at set times during the day. It can also be used to perform tasks at set time intervals, but such behaviour requires a constant and predictable system time.
You should further note that changing the system time will not prevent a task executing, unless the system time has been moved later than the allowable execution time for a particular task - which is exactly defined in the documentation, and the most correct behaviour that could be reasonably expected.
Aside from the fact that I find this behavior of the
supplied J2SE timers unacceptable, that is if the
synopsis is correct, I need to find a way around this
problem. The only reasonable course of action that I
have is to implement my own timers. Fortunately, the
impact to any dependent code at work will be isolated
since I have already abstracted the J2SE timer
dependencies from the clients.This is correct. If you want custom, specific behaviour in a context that provided system classes do not cater for, then you will need to either find an alternate implementation or build your own.
Digressing again, all waits should be performed in a while loop to prevent against spurious thread wakeup. The wait condition should hold the definitive break condition for the wait loop... in the case of an accurate timer, the break condition is that the required number of milliseconds have passed since the wait was entered. I challenge you to implement an accurate timer that is not dependent on the system time and is protected against spurious wakeup.
Spurious wakeup is not just theoretical - I have actually had to rework a non-protected wait() providing a simple delay into a time-dependent looping wait because I was experiencing consistent spurious wakeup in a particular circumstance. I still don't know what the circumstance was exactly, but double-checking against the system time meant I didn't have to (Incidentally, the spurious wakeup didn't recur, so the system was not ever reduced to polling)
As for the java.util.Timer, each timer has its
own queue which runs on a seperate VM thread. So, if
I go and create thousands of timers (ala new
java.util.Timer()) I get thousands of VM threads.Why would you expect any different? java.util.Timer supports arbitrarily many tasks being scheduled at any particular time (Subject to restrictions as mentioned in the java.util.Timer javadoc documentation), so only one Timer object needs to be created. More than one may be created, so distinct subsystems of a framework can execute completely distinct timers (ie- one subsystem's timer failing for any reason won't bring the other subsystems' timers down). If you dislike such flexibility, feel free to devise your own interface. -
can anyone tell me how to implement a timer in my program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sudoku extends JApplet implements ActionListener{
JButton button [][] = new JButton [9][9] ;
public void init()
Container container = getContentPane() ;
container.setLayout(new GridLayout(9,9));
for ( int count = 0 ; count <=8 ; count++)
for (int count1 = 0 ; count1 <=8 ; count1++ )
button [count][count1] = new JButton() ;
button [count][count1].addActionListener (this) ;
container.add(button [count][count1]);
public void actionPerformed ( ActionEvent event )
String output = "" ;
output =JOptionPane.showInputDialog ( "Enter a number between 1-9" );
if ( output.indexOf ('.') != -1 )
JOptionPane.showMessageDialog (null, "Please enter an integer between 1-9 " ) ;
else
int num = Integer.parseInt ( output ) ;
if ( num > 9 || num <1 )
JOptionPane.showMessageDialog ( null, "Re-enter an integer between 1-9" );
else
((JButton)event.getSource()).setText(output) ;
}It can be done with Treads, in the example below 3 buttons Start , Pause\Resume and Stop manipulate the timer.
public void actionPerformed(ActionEvent e){
if(e.getSource() == buttonStart) {
counterLabel.setText("0 : 0");
thread = new Thread(this);
thread.start();
buttonStart.setEnabled(false);
if(e.getSource() == buttonStop) {
thread.stop();
buttonStart.setEnabled(true);
if(e.getSource() == pauseButton) {
if(!isPaused) {
thread.suspend();
pauseButton.setLabel("Resume");
isPaused = true;
else {
thread.resume();
pauseButton.setLabel("Pause");
isPaused = false;
public void run(){
int secondCounter = 0;
int minuteCounter = 0;
while(true) {
try {
thread.sleep(1000);
catch(InterruptedException e) {}
secondCounter++;
if (secondCounter == 60) {
minuteCounter++;
secondCounter = 0;
counterLabel.setText(String.valueOf(minuteCounter) + " : " +
String.valueOf(secondCounter));
}Hope i've been of some assistance! -
Anyone can compile this program?Duke will be rewarded
Anyone can help me compile this program..I try debugging a lot of time but it is not working!
import java.lang.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ChatApplet extends Applet implements ActionListener,Runnable
String user;
String msg;
public void init() {
super.init();
//{{INIT_CONTROLS
setLayout(new BorderLayout(0,0));
addNotify();
resize(518,347);
setBackground(new Color(12632256));
msgbox = new java.awt.TextArea("",2,0,TextArea.SCROLLBARS_NONE);
msgbox.setEditable(false);
msgbox.disable();
//msgbox.hide();
msgbox.reshape(0,0,380,216);
add(msgbox);
idbox = new java.awt.TextField();
idbox.reshape(84,288,284,24);
add(idbox);
button1 = new java.awt.Button("EnterRoom");
button1.reshape(384,288,72,21);
add(button1);
list = new java.awt.List();
//list.TOP_ALIGNMENT();
//list.disable();
list = new java.awt.List(5);
list.add("#Default User"+"\n");
list.reshape(384,24,128,196);
list.setFont(new Font("Helvetica", Font.BOLD, 12));
add(list);
label2 = new java.awt.Label("Members");
label2.reshape(396,0,100,19);
add(label2);
label1 = new java.awt.Label("UserName");
label1.reshape(0,288,72,27);
add(label1);
textbox = new java.awt.TextField();
textbox.reshape(84,240,431,44);
add(textbox);
label3 = new java.awt.Label("EnterText");
label3.reshape(0,252,72,25);
add(label3);
//uf = new UserFrame();
button1.addActionListener(this);
idbox.addActionListener(this);
textbox.addActionListener(this);
list.addActionListener(this);
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==idbox)
user = idbox.getText()+"\n";
list.addItem(user.trim());
idbox.setText("");
msgbox.append(user+" HAS JOINED THE GROUP");
if(ae.getSource().equals(button1))
user = idbox.getText()+"\n";
list.addItem(user.trim());
idbox.setText("");
msgbox.append(user+" HAS JOINED THE GROUP");
if(ae.getSource().equals(textbox))
msg = textbox.getText();
msgbox.append(msg+"\n");
textbox.setText("");
if(ae.getSource().equals(list))
String l = list.getSelectedItem();
//uf.setTitle(l);
//Frame i[] = uf.getFrames();
//uf.setVisible(true);
public void start()
if(vt == null)
vt = new Thread(this,getClass().getName());
vt.start();
public void run()
try{
for(int i=0;i<10;i++)
msgbox.append("One stop Java source code - www.globalleafs.com"+"\n");
msgbox.setForeground(Color.red);
vt.sleep(30000);
vt.resume();
}catch(Exception e){e.printStackTrace();}
java.awt.TextArea msgbox;
java.awt.TextField idbox;
java.awt.Button button1;
java.awt.List list;
java.awt.Label label2;
java.awt.Label label1;
java.awt.TextField textbox;
java.awt.Label label3;
private Thread vt;The program compiles over here. It just has some deprecation warnings ...or is that what you wanted debugged?
Don't use reshape() ...I think in AWT you should now use setBounds();
Don't use list.addItem(); ...looks like the API steers us to list.add();
Don't use Thread.resume() ...I don't think there is a replacement (unneccessary?).
Gee, this program must have ran the chat program in Ford's old model T ... !! (??) -
Concurrent Access to Cache Mechanism
Below I have code from an object that is used for caching data from a database. My question deals with the method getCacheObj(). Does getCacheObj() return a copy of the reference to cacheObj or does it return the actual cacheObj variable itself?
Specifically I am concerned about a concurrency issue when the methods refreshCache() and getCacheObj() are called simultaneously. What would happen in the following situation:
Thread 1 calls findActiveByWebsiteArea() which calls getCacheObj(). getCacheObj() returns the cacheObj for processing down the line in a jsp or other java object. Prior to thread 1 finishing the processing with cacheObj, thread 2 calls refreshCache() which resets cacheObj. Is it possible for thread 2 to clash with thread 1?
public class NewsPeer extends AncestorCachePeer {
// object that will house the cached data
protected static NewsPeer cacheObj = null;
// attributes for the instantiated cache object
private Hashtable newsByWebsiteArea = null;
private NewsPeer() {
// private constructor to enforce a singleton
public static void refreshCache() throws Exception {
// reset the cache object so a fresh retrieve will be performed
// the next time the cache is accessed
synchronized (cacheObj) {
cacheObj = null;
private static NewsPeer getCacheObj() throws Exception {
synchronized (cacheObj) {
if (cacheObj == null) {
cacheObj = new NewsPeer();
cacheObj.retrieveCache();
return cacheObj;
public static List findActiveByWebsiteArea(String websiteareaId) throws Exception{
// get item from cache obj
return (List) getCacheObj().newsByWebsiteArea.get(websiteareaId);
private void retrieveCache() throws Exception {
// code to populate newsByWebsiteArea on cacheObj
}I feel it's not a good idea to make your lock object null somewhere ...
for example, let us say refreshCache() method acquired the lock.
but before it performs CacheObj = null, it gets descheduled, and another thread, runs getCacheObj() and since it
cannot get the cacheObj, it waits on cacheObj's queue, and now the previous thread resumes, which makes cacheObj null.
It will be better if you can have a separate lockObject.
This is my suggestions and I may be wrong. So let us wait for the experts to give some more suggestions.. -
JVMDI & Suspend/ResumeThread for Java simulation.
I am currently trying to add a Java Interface to a simulation software package written in C++. The JNI interface works fine. The issue is we are attempting to simulate a device that runs Java code. Therefore, when the simulation pauses, the Java code must also pause.
The simulation is a discrete simulation, so it runs in timesteps. I am attempting to force a certain number of lines of Java code to execute for each timestep. Currently, five Java steps per simulation step. The process works as follows.
Resume a suspended thread. Allow five single step events and suspend thread on the fifth.
The reason for this method is we would like to plug Java code directly into the simulation without modifiying it. For the most part, the simulation works, but it is prone to freezing.
The JNI and JVMDI interface is created from the native side. The code gets frozen sometimes when C++ resumes a thread and then Java doesn't throw any Single-Step events. The GetThreadStatus function claims the thread is running and not suspended. It often reaches up to 5000 cycles without error. The C++ side will just forever wait for the single-step events that never come.
I'm assuming this problem has to do with why suspend and resume where depricated from the Java language, but then why are they still availible to JVMDI? However, the explanation on why the functions were depricated doesn't seem to explain the error because it says the thread.resume() is never reached, but in my case it is called and doesn't return errors.
Any help would be greatly appreciated.You're right about the even being generated from the thread. I tired that. It didn't work. I have my main C++ "thread", which uses JNI to spin off a Java thread. Then when the event is called, the JVM kinda steals control away from my application. I can't return control until I exit the hook function, allowing the thread to continue execution or Suspend the thread. Executing the Suspend command actually prevents any more execution within the hook function until the Resume command is called from my application.
Unless you have an idea of how I can return control out to the C++, I'm a bit lost. The only way to do something like that, is something like a goto command which would certainly doubt would work.
Thanks for the advice. -
The code below is out of date, does anyone to where the update API's are, i can't find them at all.
// event handling for keys down
public boolean keyDown (Event e, int key)
if(key == Event.LEFT)
key_left = true;
player.playerWalkLeft(true);
else if (key == Event.RIGHT)
key_right = true;
player.playerWalkRight(true);
else if (key == 97)
key_space = true;
player.playerJump(true);
return true;
// event handling for keys up
public boolean keyUp(Event e, int key)
if(key == Event.LEFT)
key_left = false;
player.playerWalkLeft(false);
else if(key == Event.RIGHT)
key_right = false;
player.playerWalkRight(false);
else if (key == 97)
key_space = false;
player.playerJump(false);
return true;
// Stop Thread
public void stop()
th.stop();
// Stop Thread
public void destroy()
th.stop();
}Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
Resources for learning about threads:
Java's Thread Tutorial
JavaWorld: Introduction to Java threads
Java? API Specifications
Java? 1.5 JDK Javadocs
~
Maybe you are looking for
-
How can I make a sub menu go up instead of down?
Client wants the menu pinned to the bottom of the page but when you hover over SERVICES the sub menus go down (off the page). Is there a way to make the menu go UP so they are readable? HOME
-
Iphone 5 has started powering down after upgrade to 7.02, help please.
My iPhone 5 started powering down after the 7.02 upgrade I did almost a week ago (3 times). I realize now that it starts after I see a message notification on the home screen and click on the slider to enter my passcode and reply to the message. I n
-
Where Do I Enter DNS Numbers?
I have an imac and Macbook Pro that both connect wirelessly through a snow base-station connected by ethernet cable to a dsl modem. This set up normally works perfectly but occasionally I will experience some slow connection issues which I believe ar
-
I forgot the administrator password what can i do to recover?
i need your help the last week mi brother bought me a imac he started the imac but he dont put a password to the administrator, and now when i try to put the new programs on mi imac they ask me for a password to the administrator account
-
I had google as my search engine for a number of years, but now when I type in anything Bing comes up. I went to prefernces and google is checked off as the search engine. Anything I can do to get back to google and not use bing? Thanks for any ass