Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...