[英]in java multithread applet all threads draw on same object
it is my very first time to write a java applet; 这是我第一次编写Java小程序。 I have my multithread program and I must create an applet that shows the operation of program;
我有我的多线程程序,并且必须创建一个小程序来显示程序的操作。 in this moment I try to create a very basic applet that "simply" print the name of each thread.
在这一刻,我尝试创建一个非常简单的小程序,“简单地”打印每个线程的名称。
My problem is that all threads draw on same object and overwrite this, I want that each thread write the own name separately (in this moment I can see only the name of last thread). 我的问题是所有线程都在同一个对象上绘制并覆盖此对象,我希望每个线程分别编写自己的名称(此刻我只能看到最后一个线程的名称)。
I've tried to create another graphics object but not working (and i think not is the right way). 我试图创建另一个图形对象,但是不起作用(我认为不是正确的方法)。
This is the structure of my applet: I created a listener that is the interface and a responder that extends Applet and implements listener, in this I have init(), paint(Graphic g) and implementation of the function from listener's interface, the structure is: 这是我的applet的结构:我创建了一个侦听器,该接口是一个接口,一个响应器扩展了Applet并实现了侦听器,在这里,我有init(),paint(Graphic g)和侦听器接口的功能实现,结构是:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class Responder extends Applet implements Listener {
public void init(){
//some initialization
for(int i=0; i<10; i++){
TH created = new TH(this); //this=receiver
created.start();
}
}
String toPrint;
int pos=0;
public void paint(Graphics g){
g.drawString(toPrint, 20, pos);
}
@Override
public void test(String s){
toPrint=s;
pos+=10;
repaint();
}
}
and each thread calls "test" function 每个线程都调用“测试”功能
Result is that in applet I have only one string with the name of last thread. 结果是在applet中,我只有一个带有最后一个线程名称的字符串。 I've searched in the web but can't find a clear example.
我在网上搜索过,但找不到清晰的示例。
Can anyone suggest me the right way? 有人可以建议我正确的方法吗?
thanks (and sorry if there are english errors) 谢谢(对不起,如果有英语错误)
Edit: Image to be clear 编辑: 图像要清晰
Your problem is here 你的问题在这里
for(int i=0; i<10; i++){
TH created = new TH(this); //this=receiver
created.start();
}
You created 10 different threads and pass the same applet object in constructor. 您创建了10个不同的线程,并在构造函数中传递了相同的applet对象。 You need something liske this:
您需要一些这样的东西:
for(int i=0; i<10; i++){
TH created = new TH(new Responder());
created.start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.