Drawing Thread and join()
Hi, I need some hints about Threads.
I have a Thread that does some computations and then draws on a Graphics object.
I need the main program to wait until the Thread finish its computation.
If i call:
myThread.join()
from the main control flow, it correctly waits but I can't see anything drawn on the screen.
If I instead don't call join the draw is correct but obviously I don't have a correct execution
of the program.
Where am I doing a mistake?
Ok having read the other thread, I'll try to take a stab at helping you:
My understanding of the problem: You require a GUI with a button that will start an algorithm (locate) and will paint back progress to the GUI as it goes.
How to go about doing this:
You have one thread, the thread that is started when you start your program. We call this the EDT (the Event dispatching thread). The EDT should not be blocked by heavy, lengthy calls, as it is responsible for "refreshing" or repainting the GUI.
So, when someone clicks your Button, you must:
-Start a new thread like this (this is from my head, so the code may be wrong) :
new Thread( new Runnable() {
public void run() {
locate();
}).start();Call this new thread the WORKER thread
Now, each time you want to update the GUI from your WORKER thread (your algorithm), you need to do two things:
-change some state of your main running class, to tell the GUI what it should draw next time it's asked. What was suggested in that other post was that you should maintain a list of "steps" in a Collection of some sort.
-prompt the main container that your drawing to to redraw, using repaint() or something (sorry, it's been years since I've used Swing or AWT).
So, your WORKER thread updates the abstract model of what your GUI SHOULD show, but when your WORKER calls repaint(), the EDT prompts your class to redraw.
As for general concepts with threads, I'll give you one example of how to handle things asynchronously. Say you had this simple Java snippet:
public void someMethod()
doSomethingBefore();
doSomethingLengthy();
doSomethingAfter();
}And you wanted to doSomethingLengthy in a separate thread. You would use something that we call "callbacks". This implements a callback using the Runnable interface:
public void someMethod()
doSomethingBefore();
final Runnable callback = new Runnable() {
public void run() {
doSomethingAfter();
new Thread( new Runnable() {
public void run() {
doSomethingLengthy();
callback.run();
}.start();
}So what's the execution look like?
Thread1 executes someMethod()
Thread1 executes doSomethingBefore()
Thread1 starts Thread2 and then immediatly exits someMethod()
Thread2 executes doSomethingLengthy()
Thread2 executes callback.run()
Thread2 executes doSomethingAfter()
Similar Messages
-
Inability to draw simple graphics in Java properly (threads and JFrame)
I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class TestDraw extends JFrame implements Runnable {
//DECLARE VARIABLES
private JLabel lblText;
private JButton btnBegin;
private JPanel contentPane;
private int CoordX, CoordY,SizeX, SizeY, Colour; // Co'ords for drawing the squares
Random random = new Random(); // Random numbers (for square dimensions and colours)
int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4; // The different ranges of randoms I require
Thread squares = new Thread(this); // Implements a new thread
//END OF DECLARE VARIABLES
// CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
public TestDraw() {
super();
initializeComponent();
this.setVisible(true);
// INITIALISATION PROCEDURE CALL
private void initializeComponent() {
lblText = new JLabel();
btnBegin = new JButton();
contentPane = (JPanel)this.getContentPane();
// lblText
lblText.setText("This should draw squares on screen...");
// btnBegin
btnBegin.setText("Start");
btnBegin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnBegin_actionPerformed(e);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, lblText, 10,300,364,18);
addComponent(contentPane, btnBegin, 144,10,101,28);
// TestDraw
this.setTitle("TestDraw Program for CM0246");
this.setLocation(new Point(0, 0));
this.setSize(new Dimension(390, 350));
// POSITION COMPONENTS ON SCREEN
private void addComponent(Container container,Component c,int x,int y,int width,int height) {
c.setBounds(x,y,width,height);
container.add(c);
// EVENT HANDLING PROCEDURES
private void btnBegin_actionPerformed(ActionEvent e) {
System.out.println("\nAction Event from btnBegin called...");
squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
// THE MAIN METHOD (STARTS THE PROGRAM)
public static void main(String[] args) {
TestDraw bobdole = new TestDraw();
// THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
public void run() {
System.out.println("Thread running if this prints");
while(true) {
int int_1 = random.nextInt(n_1); // chooses random int for X co'ord
int int_2 = random.nextInt(n_2)+70; // chooses random int for Y co'ord
int int_3 = random.nextInt(n_3)+10; // chooses random int for X dimension
int int_4 = random.nextInt(n_3)+10; // chooses random int for Y dimension
CoordX = int_1;
CoordY = int_2;
SizeX = int_3;
SizeY = int_4;
repaint();
try {
squares.sleep(500);
catch (InterruptedException e) {
System.out.println(e);
// THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
public void paint( Graphics g ) {
System.out.print("Colour" + Colour);
g.setColor(Color.blue);
g.fillRect(CoordX, CoordY, SizeX, SizeY);
// END OF PROGRAMI don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
But if you do overload paint, make sure you call super.paint before doing anything else.
More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html -
A problem with Threads and MMapi
I am tring to execute a class based on Game canvas.
The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
The MIDI tone "Stammers".
How to over come the problem?
Thanks in advance
Kobi
See Code example below:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
public class MainScreenCanvas extends GameCanvas implements Runnable {
private MainMIDlet parent;
private boolean mTrucking = false;
Image imgBackgound = null;
int imgBackgoundX = 0, imgBackgoundY = 0;
Player player;
public MainScreenCanvas(MainMIDlet parent)
super(true);
this.parent = parent;
try
imgBackgound = Image.createImage("/images/area03_bkg0.png");
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
catch(Exception e)
System.out.println(e.getMessage());
* starts thread
public void start()
mTrucking = true;
Thread t = new Thread(this);
t.start();
* stops thread
public void stop()
mTrucking = false;
public void play()
try
InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
player = Manager.createPlayer(is, "audio/midi");
player.setLoopCount(-1);
player.prefetch();
player.start();
catch(Exception e)
System.out.println(e.getMessage());
public void run()
Graphics g = getGraphics();
play();
while (true)
tick();
input();
render(g);
* responsible for object movements
private void tick()
* response to key input
private void input()
int keyStates = getKeyStates();
if ((keyStates & LEFT_PRESSED) != 0)
imgBackgoundX++;
if (imgBackgoundX > 0)
imgBackgoundX = 0;
if ((keyStates & RIGHT_PRESSED) != 0)
imgBackgoundX--;
if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
* Responsible for the drawing
* @param g
private void render(Graphics g)
g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
this.flushGraphics();
}You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
Problem with threads and ProgressMonitor
Dear Friends:
I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
But I need deactivate the main class(the main class is the user interface) until the thread ends.
I use something like this:
LongTask myTask=new LongTask();
myTask.start();
myTask.join();
Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
What's wrong?Is the dialog a modal dialog? This can block other UI updates.
In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating -
Hi,
what is the differnce between view and join tableHi,
There are 4 types of views in SAP.
Database View - To club more than one table
Projection View - To hide fields in one table
Maintenance View - To maintain database records in table
Help View - To provide help for a fields (Same functionality as Search help. This is outdated)
View are improves performance in the following aspects
1. If you want to use more than two table in 'JOIN' condition better to use Views . It will improves performance of a program
2. If you want to use mutiple FOR ALL ENTRIES clause, better to club all SELECT statement in a view.
Note:
1.Views does not contain data in it. It fetches data from the database only depending on the condition ...
2.Views are part of data dictionary. They are a window to view the data in database
3.views can be used to give security to data. users can be allowed to view only basic data only
For More Info,go thru this Threads,
join
Views vs Inner Join
Regards,
Padmam. -
Hi, somebody knows how to edit a file that I created in corel draw 11 and I need to edit like PDF!!!! is so simple and nobody knows howwwwwwwwwwww!!!!
See your other thread.
-
Select and join one month record
I receive a request from my customer . He want generate a total sales record for a month and those data stored in daily sales table and customer table.
tblcustomer-20140101
tblcustomer-20140102
tblcustomer-20140103
tblcustomer-20141231
tblsales-20140101
tblsales-20140102
tblsales-20140103
tblsales-20141231
is there anyway when user select month name from application(ex: April), it will choose all april record and join it together?Hi kjleong,
Generally to say, it is not a good practice to store the same entity data individually for each day, there are many shortages, such as the problem you posted in this thread. You can put all of them into one table and tag them with a DATE column. Anyway
in this case, to achieve your requirement, you may refer the below stored procedure(SP).
CREATE PROC ProcGetSales
@Year VARCHAR(20),
@Month VARCHAR(20)
AS
DECLARE @Date DATE;
DECLARE @Days INT;
DECLARE @SqlStr NVARCHAR(MAX);
SET @Date = @Year+'-'+@Month+'-01';
SET @Days = DATEDIFF(DAY,@Date,DATEADD(MM,1,@Date)); --get the days of the specific month
create a temp table
CREATE TABLE #Temp
col1 int --you should put the columns after join in your real envrioment here
table join statement, put the join result into a temp table
I dont know the columns so I use * here and the join condition is just based on assumption
you should modify the statement basing on your real environment
SET @SqlStr= 'INSERT INTO #Temp SELECT * FROM [tblcustomer-WhichDay] tc JOIN [tblsales-WhichDay] ts ON tc.customerID = ts.customerID';
DECLARE @Counter INT = 1;
WHILE @Counter <= @Days --loop the tables named after the specific month
BEGIN
DECLARE @Sql NVARCHAR(MAX) = REPLACE(@SqlStr,'WhichDay',CONVERT(VARCHAR(8),CAST(@Year+'-'+@Month+'-'+LTRIM(STR(@Counter)) AS DATE),112));
EXEC sp_executesql @Sql;
SET @Counter = @Counter+1;
END
SELECT * FROM #TEMP
The SP is not ready to use, you have to make some modification basing on your real environment before it works.
If you have any question, feel free to let me know.
Best regards,
Eric Zhang
If you have any feedback on our support, please click
here. -
Kill a thread and remove the element from the vector
Hi All
I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
However, I want to delete this element from the Vector now.
Can someone please throw some light on this?
Here the code I have written for this:
try
System.out.println(counter);
int xCoord = generator.irand(25,200); // X-coord of AP
int yCoord = generator.irand(25,200); // Y coord of AP
listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
for(int i=0;i<vnuBS.returnBSList().size();i++)
if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
double c = exponential() * 10000;
long timeToService = (long)c;
System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
vnuBS.returnBSList().get(i).reduceChannelCounter();
System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
mobileNodesThread.elementAt(mobileNodeCounter).start();
mobileNodesThread.elementAt(mobileNodeCounter).join(100);
// System.out.println("Died");// thread dies after join(t) milliseconds.
System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
listMN.remove(this.listMN.lastElement()); //dropcall
System.out.println("Removed "+mnId);
removeCounter++;
mnId = mnId--;
mobileNodeCounter--;
mnId = mnId+1;
Thanks a lot.I'm not sure if what you are trying to accomplish is correctly implemented.
The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish? -
Example of WAIT and CONTINUE using checkBox and thread and getTreeLock()
I had so much trouble with this that I descided to
post if incase it helps someone else
// Swing Applet example of WAIT and CONTINUE using checkBox and thread and getTreeLock()
// Runs form dos window
// When START button is pressed program increments x and displys it as a JLabel
// When checkBox WAIT is ticked program waits.
// When checkBox WAIT is unticked program continues.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Wc extends JApplet {
Display canvas;//drawing surface is displayed.
Box buttonPanel;
Box msgArea;
public static JButton button[] = new JButton [2];
public static JCheckBox checkBox[] = new JCheckBox[2];
public static JLabel msg[] = new JLabel [2];
String[] buttonDesc ={"Start","Quit"};
public static final int buttonStart = 0;
public static final int buttonQuit = 1;
String[] checkBoxDesc ={"Wait"};
public static final int checkBoxWait = 0;
public boolean wait;
public Graphics g;
//================================================================
public static void main(String[] args){
Frame f = new Frame();
JApplet a = new Wc();
f.add(a, "Center"); // Add applet to window
a.init(); // Initialize the applet
f.setSize(300,100); // Set the size of the window
f.show(); // Make the window visible
f.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){System.exit(0);}
}// end main
//===================================================
public void init() {
canvas = new Display();
setBackground(Color.black);
getContentPane().setLayout(new BorderLayout(3,3));
getContentPane().add(canvas, BorderLayout.CENTER);
buttonPanel = Box.createHorizontalBox();
getContentPane().add(buttonPanel, BorderLayout.NORTH);
int sbZ;
// add button
button[0] = new JButton(buttonDesc[0]);
button[0].addActionListener(canvas);
buttonPanel.add(button[0]);
button[1] = new JButton(buttonDesc[1]);
button[1].addActionListener(canvas);
buttonPanel.add(button[1]);
// add checkBox
sbZ=0;
checkBox[sbZ]=new JCheckBox(checkBoxDesc[sbZ]);
checkBox[sbZ].setBackground(Color.white);
checkBox[sbZ].setOpaque(true);
checkBox[sbZ].addActionListener(canvas);
buttonPanel.add(checkBox[sbZ]);
msgArea = Box.createVerticalBox(); // add message
sbZ=0;
msg[sbZ]=new JLabel("1",JLabel.LEFT);
msg[sbZ].setOpaque(true);
msg[sbZ].setBackground(Color.black);
msg[sbZ].setForeground(Color.red);
msgArea.add(msg[sbZ]);
getContentPane().add(msgArea, BorderLayout.SOUTH);
} // end init();
//===================================================
public void stop(){canvas.stopRunning();}
//===================================================
// The following nested class represents the drawing surface
// of the applet and also does all the work.
class Display extends JPanel implements ActionListener, Runnable {
Image OSI;
Graphics OSG; // A graphics context for drawing on OSI.
Thread runner; // A thread to do the computation.
boolean running; // Set to true when the thread is running.
public void paintComponent(Graphics g) {
if (OSI == null) {
g.setColor(Color.black);
g.fillRect(0,0,getWidth(),getHeight());
else {g.drawImage(OSI,0,0,null);}
}//paintComponent
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (command.equals(buttonDesc[buttonStart])) {
startRunning();
if (command.equals(buttonDesc[buttonQuit])) {
stopRunning();
if (command.equals(checkBoxDesc[checkBoxWait])){
System.out.println("cb");
if (checkBox[checkBoxWait].isSelected() ) {
wait = true;
System.out.println("cb selected twait "+wait);
return;
wait = false;
synchronized(getTreeLock()) {getTreeLock().notifyAll();}
System.out.println("cb selected fwait "+wait);
} // end command.equal cb wait
} //end action performed
// A method that starts the thread unless it is already running.
void startRunning() {
if (running)return;
// Create a thread that will execute run() in this Display class.
runner = new Thread(this);
running = true;
runner.start();
} //end startRunning
void stopRunning() {running = false;System.exit(0);}
public void run() {
button[buttonStart].setEnabled(false);
int x;
x=1;
while(x>0 && running){
x = x + 1;
msg[0].setText(""+x);
try{SwingUtilities.invokeAndWait(painter);}catch(Exception e){}
//importand dont put this in actionPerformed
if (wait) {
System.out.println("run "+wait);
synchronized(getTreeLock()) {
while(wait) {
System.out.println("while "+wait);
try {getTreeLock().wait();} catch(Exception e){break;}
} //end while(wait)
} // end sync
} // end if(wait)
} // endwhile(x>0)
stopRunning();
} // end run()
Runnable painter = new Runnable() {
public void run() {
Dimension dim = msg[0].getSize();
msg[0].paintImmediately(0,0,dim.width,dim.height);
Thread.yield();
}//end run in painter
} ; //end painter
} //end nested class Display
} //end class WcI just encountered a similar issue. I bought a new iPhone5s and sent my iPhone4s for recycling as it was in great shape, no scratches, no breaks, perfect condition. I expected $200 and received an email that I would only receive $24.12. The explanation was as follows: Phone does not power on - Power Supply Error. Attempts to discuss don't seem to get past a customer service rep that can only "escalate" my concern. They said I would receive a response, but by email. After 4 days no response. There is something seriously wrong with the technical ability of those in the recycling center.
-
How to implement BINDING between drawing shapes and properties?
See this background info:
Can we have BINDING between drawing shapes and properties?
This needs more specific info. My application reads a number of XML files, and places the data in an Excel worksheet. Let's say that there are 20 XML files, the app creates 20 lower tabs (spreadsheets) named: "Item 1", "Item 2", ...,
"Item 20".
That is the current version. I am told by the users, however, that in some cases there are some XML files which create more than 1 Excel lower tab. For example, the file: "Items 8-11.xml" needs to fill tabs 8, 9, 10 and 11.
In that particular case the user will modify the default map (a 45-degree diagonal, equivalent to the
identity function F(x) = x), by clicking around. The resulting new map will look as follows:
Since the number of XML files does not change, the number of rows is constant. However, each time a black square is moved from its canonical (45-degree) location, a spreadsheet becomes "orphan" and therefore the application must create a new Excel
lower tab (which is a grid column). IOW: The number of columns keeps on growing to the right.
List<Model>
I figure that (as opposed to DataGrids which grow and shrink vertically, which each Model being 1 row) this thing should use the column as fundamental Model.
Before running the main app (the XML file reading procedures), the user will select a menu item named "Configure XML to Excel Mapping" and an interface similar to the image above will be shown.
In addition to the property binding, which has been discussed, how should I implement the drawing and erasing of black and white squares? I guess I will need some sort of "ConvertTo" bidirectional bridge from/to boolean and square drawing?You lost me with the xml file and the tab and the wossname to the thingummybob.
I don't follow the explanation, sorry.
The way to show stuff like that isn't dependent on how the data is stored where though.
I probably wouldn't draw them, as such.
I'd probably just make each a usercontrol which bound the fill brush of a rectangle for the black white bit and used a border for the outline.
To simplify that:
<Grid> <Border>
<Rectangle Fill={Binding FillBrush}"/>
</Border>
</Grid>
FillBrush
Would be a public property solidcolorbrush exposed from your cellvm
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using GalaSoft.MvvmLight;
namespace wpf3
public class CellVM : ViewModelBase
private SolidColorBrush fillBrush;
public SolidColorBrush FillBrush
get { return fillBrush; }
set
fillBrush = value;
RaisePropertyChanged();
You can then have some logic somewhere which tells that viewmodel to show black or white fill. Which would be that converter bridge thingy equivalent. This thing is true then FillBrush = whiteBrush else FillBrush = blackBrush.
You could probably do it with just rectangle, lose the border and set the Stroke on the rectangle.
The stroke is the outside line round a rectangle ( or any shape).
https://msdn.microsoft.com/en-us/library/system.windows.shapes.shape.stroke(v=vs.110).aspx
And you would of course do other stuff like sizing the usercontrol and arranging an list in a list as I explained in your other thread.
Oh.................
But to answer the question in the title.
Yes you can bind all sorts of things including the point making up a polygon, brush used to draw the line and all sorts. You could even do flashing cells if you wanted.
Hope that helps.
Recent Technet articles: Property List Editing;
Dynamic XAML -
Difference between implements thread and ex
what is the difference between extending the thread and implements the runnable interface..?
Not much. One reason to prefer implementing the Runnable interface as oppossed to extending Thread is to allow your class to extend a diifferent base class if you choose to do so. Since Java supports single implementation inheritance it is always a good idea to implement Runnable as oppossed to extending Thread in case you want to extend some other class, besides Thread, now or in the future.
Some OO purists may also claim that unless your class (that extends Thread) "is a" specialized Thread that extending Thread breaks the OO sematics of the "is a" relationship that inheritance is suppossed to represent. For instance a widget class that draws a pixel randomly on the screen that needs to be run in it's own Thread really isn't a specialized Thread class. -
AirTime / Threads and resulting problems
Hi,
i ve written something like a proprietary webservice to authenticate a user. So consider this code:
MyHTTPRequest request = new PlayerRequest("authenticateLogin");
request.addParameter("login", playername);
request.addParameter("password", password);
request.execute();
if (!request.isError()) {
Player[] playerArray = (Player[]) request.createObjectsFromHTTP();
player = playerArray[0];
} else {
player = null;
}execute() fires a new Thread and does the HTTP stuff. Now the Emulator shows the AIRTIME yes/no Screen. It locks because isError() contains a join(), this is because isError() must wait for the HTTP connection to finish to see what happened.
When i leave out the join() in the isError() method, i can answer the yes/no screen, but then my isError() gets a NullPointer, because the request is not finished.
So i have a situation, where i cant go on in my code before the HTTPRequest is ended, but i must be able to answer the yes/no screen.
I tried several things like a loop in the code above which asks if the thread from PlayerRequest is still running but as soon i do something like this, i got my deadlock on yes/no screen again.
Any suggestions?thats exactly the problem why you have to use Threads. The main thread has first to be finished, before the networking thread can be started. By using join() you make the use of Threads obselete since this must be processed sequentially (because the main thread waits for the networking thread, in your implementation). Finally, for this what you want to do using threads is senseless, but they are mandatory for MIDP 2.0.
Okay, now for the solution ;)
You have to initiate the processing of the result from your networking thread. That means the main thread finishes and does nothing (or displays a gauge or sth). After the networking, the networking thread calls something like "processResult()" and thus gives the control back to the main thread. This is the principle of using threads: that they can work asynchronously and (more or less) independent from another.
hth
Kay -
Having a problem with threads and using locks
I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
Withdrawal Threads Deposit Threads Balance
Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
Thread 1 deposits $187 $187
Thread 3 deposits $169 $356
Thread 5 deposits $61 $417
Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
/************Assign2_Main.java************/
import java.util.concurrent.*;
public class Assign2_Main
{//start Assign2_Main
public static void main(String[] args)
{//start main
// create ExecutorService to manage threads
ExecutorService threadExecutor = Executors.newCachedThreadPool();
Account account = new SynchronizedThreads();
Deposit deposit1 = new Deposit(account, "Thread 1");
Deposit deposit2 = new Deposit(account, "Thread 3");
Deposit deposit3 = new Deposit(account, "Thread 5");
Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
System.out.println("------------------\t\t---------------\t\t\t-------\n");
try
threadExecutor.execute(withdrawal1);
threadExecutor.execute(deposit1);
threadExecutor.execute(withdrawal2);
threadExecutor.execute(deposit2);
threadExecutor.execute(withdrawal3);
threadExecutor.execute(deposit3);
threadExecutor.execute(withdrawal4);
catch ( Exception e )
e.printStackTrace();
//shutdown worker threads
threadExecutor.shutdown();
}//end main
}//end Assign2_Main/******************Withdrawal.java****************************/
public class Withdrawal implements Runnable
{//start class Withdrawal
*constructor
public Withdrawal(Account money, String n)
account = money;
name = n;
public void run()
{//start ruin
int newNum = 0;
newNum = account.getBalance(name);
Thread.yield();
}//end run
private Account account;
private String name;
}//end class Withdrawal/*******************Deposit.java***************/
import java.util.Random;
public class Deposit implements Runnable
{//start class Deposit
*constructor
public Deposit(Account money, String n)
account = money;
name = n;
public void run()
{//start run
try
Thread.sleep(100);
account.setBalance(random.nextInt(200), name);
}// end try
catch (InterruptedException e)
e.printStackTrace();
}//end run
private Account account;
private Random random = new Random();
private String name;
}//end class Deposit/********************Account.java*****************/
*Account interface specifies methods called by Producer and Consumer.
public interface Account
//place sum into Account
public void setBalance(int sum, String name);
//return value of Account
public int getBalance(String name);
} /**************SynchronizedThreads.java****************/
import java.util.concurrent.locks.*;
import java.util.Random;
public class SynchronizedThreads implements Account
{//start SynchronizedThreads
*place money into buffer
public void setBalance(int amount, String name)
{//start setBalance
// lock object
myLock.lock();
sum += amount;
System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");
//threads are singnaled to wakeup
MakeWD.signalAll();
// unlock object
myLock.unlock();
}//end setBalance
*gets the balance from buffer
public int getBalance(String name)
{//start getBalance
int NewSum = random.nextInt(50);
//lock object
myLock.lock();
try
if(sum > NewSum)
//takes NewSum away from the account
sum -= NewSum;
System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
else
System.out.println(name + " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");
//not enough funds so thread waits
MakeWD.await();
//threads are singnaled to wakeup
MakeD.signalAll();
}//end try
catch (InterruptedException e)
e.printStackTrace();
finally
//unlock object
myLock.unlock();
return NewSum;
}//end getBalance
private Random random = new Random();
private Lock myLock = new ReentrantLock();
private Condition MakeD = myLock.newCondition();
private Condition MakeWD = myLock.newCondition();
private int sum = 0;
}//end SynchronizedThreadsYou can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
WWhen I set up family sharing i did it with me as family organizer, but as my spouse is the organizer I had to leave the "family" I created and join his. But while setting it up an error occurred, and the screen went blank. Now I tried to join his family sharing again, and my phone keeps telling me I can't because accounts can only join families twice a year.
I Don't really want to wait 364 days from now, is there a way in which I can reset my accoint so I can join family sharing again?
Apple support doesn't have a solution for me yet!
KInd regardsThis morning I looked at my family sharing account again an IT WORKS NOW! Think Apple has done a reset to my account, though I'm not exactly sure why! So I hope it works for you guys as well!
-
Multiple rows Converge to Single row and join
Hi Folks,
I am facing a tricky challenge to join a table with multiple rows and converge into a single row (based on ID, period) and join with another table to get a single row. Let me explain.
Table 1: DTL_TABLE (id, period, course, names, title, type)
1 2010 mat john null null
1 2010 mat jim null null
1 2010 cam null officer null
1 2010 cam null Prof null
1 2010 phy null null Inclass
1 2010 phy null null Online
Join with
Table 2: ID_TABLE(id, period, Loc, Dept, Code)
1 2010 nj 101 CC.
Output format (id, period, course, names, title, type, Loc, Dept, Code)
result : 1 2010 mat,cam,phy john,jim officer,prof inclass,online nj 101 CC
I have created all the DDLs and DMLs if that help. Kindly let me know if a Join SQL query is possible.
Thank you,
Aj
CREATE TABLE DTL_TABLE
ids VARCHAR2 (10),
period VARCHAR2 (10),
course VARCHAR2 (10),
names VARCHAR2 (10),
title VARCHAR2 (10),
TYPE VARCHAR2 (10)
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'mat',
'jim',
NULL,
NULL);
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'mat',
'john',
NULL,
NULL);
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'mat',
'kale',
NULL,
NULL);
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'cam',
NULL,
'officer',
NULL);
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'cam',
NULL,
'prof',
NULL);
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'phy',
NULL,
NULL,
'inclass');
INSERT INTO DTL_TABLE
VALUES ('1',
'2010',
'phy',
NULL,
NULL,
'online');
COMMIT;
CREATE TABLE id_table
ids VARCHAR2 (10),
period VARCHAR2 (10),
loc VARCHAR2 (10),
dept VARCHAR2 (10),
code VARCHAR2 (10)
INSERT INTO id_table
VALUES ('1',
'2010',
'nj',
'101',
'cc');
COMMIT;Aj09 wrote:
Hi Folks,
I am facing a tricky challenge to join a table with multiple rows and converge into a single row (based on ID, period) and join with another table to get a single row. Let me explain.
Table 1: DTL_TABLE (id, period, course, names, title, type)
1 2010 mat john null null
1 2010 mat jim null null
1 2010 cam null officer null
1 2010 cam null Prof null
1 2010 phy null null Inclass
1 2010 phy null null Online
Join with
Table 2: ID_TABLE(id, period, Loc, Dept, Code)
1 2010 nj 101 CC.
Output format (id, period, course, names, title, type, Loc, Dept, Code)
result : 1 2010 mat,cam,phy john,jim officer,prof inclass,online nj 101 CC
I have created all the DDLs and DMLs if that help. Kindly let me know if a Join SQL query is possible.
SELECT TBL.id,
DTLperiod,
course,
names,
title,
TYPE,
Loc,
Dept,
Code
FROM ID_TABLE TBL,
DTL_TABLE DTL
WHERE TBL.ID = DTL.ID
AND TBL.PERIOD = DTL.PERIOD; it not good to use RESERVED WORDS like "ID" or "TYPE" as column names
Maybe you are looking for
-
New ipod gen.4... itunes on old computer with windows xp... comp. wont recognize ipod touch... when plugged into usb port... put music on external hard drive ..... now must transfer to laptop...with windows vista home premium... help
-
Problem while releasing Request
Hello All, In one of our client's DEV Server, we are facing problem while releasing requests. When I release a request it is not appearing in the PRD import Queue. When I checked the TMS Alert Viewer, it is showing as" TP REPORTED ERROR" And more ove
-
Operations are not scheduled correctly
Hello All, Need your Help. We are facing issue on on operation scheduling between R/3 & APO. Before migrating to APO, a operation use to get schedule in 10 days whereas after migrating same part to APO , same operation takes aprox 15 days time. Here
-
Mail/Browser applications keep reseting to Default Apps
Gents, After restarting my computer, the mail/internet browser/pdf viewer applications keep reseting themselves to the default applications: Entourage goes back to Mail Firefox goes back to Safari Acrobat goes back to Preview Why is this happening? i
-
Does the Adobe Color Theme have a scroll bar?
I can't view and explore all the themes from the color theme panel in Adobe In design? I only see some of them. When I try to drag down to see other themes I can't. The answer to my question might be simple but I can't seem to find it. Please help.