java 等待多少秒_Java:定时器(等待x秒)

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值