简体   繁体   中英

in java multithread applet all threads draw on same object

it is my very first time to write a java applet; 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:

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. 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. You need something liske this:

 for(int i=0; i<10; i++){
    TH created = new TH(new Responder());
    created.start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM