class runnable implements Runnable {
private Object obj;
public runnable(Object obj)
{
this.obj = obj;
}
public void run() {
try {
Thread.sleep(3000);
this.obj.setText("");//right here just execute your method
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!"); //your code here
}
}
public class Test {
public static void main(String[] args){
Object myObject;
(new Thread(new runnable(myObject))).start();
}
}
你可以启动另一个线程来处理这个问题。只要在另一个线程中进行处理即可。睡3秒钟,然后清除lbl。
这里有一个例子展示它是如何工作的:
class runnable implements Runnable {
Test test;
public runnable(Test test)
{
this.test = test;
}
public void run() {
try {
Thread.sleep(3000);
this.test.test = "test2";
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!");
}
}
public class Test {
public String test = "test";
public static void main(String[] args) throws InterruptedException{
Test test = new Test();
System.out.println(test.test);
(new Thread(new runnable(test))).start();
Thread.sleep(4000);
System.out.println(test.test);
}
}
****************************** ****************************** UPDATE ******************* ******************************************
class runnable implements Runnable {
Test test;
public runnable(Test test)
{
this.test = test;
}
public void run() {
try {
Thread.sleep(3000);
this.test.label.setText("This is a test.");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!");
}
}
public class Test {
public String test = "test";
JLabel label = new JLabel("Test");
JFrame frame = new JFrame();
JButton button = new JButton();
public static void main(String[] args) throws InterruptedException{
Test test = new Test();
test.label.setText("Test");
test.button.setText("Test Button");
test.button.setSize(50, 50);
test.frame.setSize(500, 500);
test.frame.add(test.button);
test.frame.add(test.label);
test.frame.setVisible(true);
test.button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
(new Thread(new runnable(test))).start();
}
}