Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

java - JTextArea thread safe?

I have some code that does some initialization (including making a JTextArea object), starts three separate threads, and then these threads try to update the JTextArea (i.e. append() to it), but its not working at all. Nothing shows up on the JTextArea (however, during the initialization, I print some test lines onto it, and that works fine). What's going on? How can I fix this? Also, each of those threads sleeps a random amount of time every time it has to update the JTextArea.

Sorry I haven't provided any code, its all spread out over several files.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although I believe the API has stated that JTextArea#append(...) is thread safe, I've heard of problems with it and would recommend that this only be called on the EDT. The classic example of this is to use a SwingWorker and append to the JTextArea in the process method by calling publish.

For me, it'll be hard to make any specific suggestions to you though without code. I do have to wonder though if you're putting the EDT to sleep somewhere in your code.

Edit: as per your comment check out this tutorial: Concurrency in Swing


Edit 2: as per comment by Tim Perry, loss of thread safety and the reasoning behind this has been posted in this Java bug and which has to do with this line of code where text is added to the JTextArea's Document:

doc.insertString(doc.getLength(), str, null);

The line decomposes into two lines:

  1. int len=doc.getLength();
  2. doc.insertString(len,str,null);

The issue is that a problem can occur if the Document, doc, changes between lines 1 and 2, especially the Document length.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...