你好,游客 登录 注册 搜索
背景:
阅读新闻

Android开发中的多线程

[日期:2014-09-29] 来源:Linux社区  作者:Gaojiecai [字体:大 中 小]

Java中的实现线程体方式2

  上面介绍继承Thread方式实现线程体,下面介绍另一种方式,这种方式是提供一个实现接口Runnable的类作为一个线程的目标对象,构造线程时有两个带有Runnable target参数的构造方法:

  Thread(Runnable target);

  Thread(Runnable target, String name)。

  其中的target就是线程目标对象了,它是一个实现Runnable的类,在构造Thread类时候把目标对象(实现Runnable的类)传递给这个线程实例,由该目标对象(实现Runnable的类)提供线程体run()方法。这时候实现接口Runnable的类仍然可以继承其他父类。

请参看代码清单,这是一个Java AWT的窗体应用程序。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class textThread2 extends Frame implements Runnable, ActionListener {

    public Label label;
    public Button button;
    public Thread ClockThread;
    public boolean isRunning;
    public int timer = 0;

    public textThread2() {
        button = new Button("停止计时器");
        label = new Label("计算器启动");
        button.addActionListener(this);
        setLayout(new BorderLayout());
        add(button, "North");
        add(label, "Center");
        setSize(320, 480);
        setVisible(true);

        // textThread2 textThread2 = new textThread2();
        ClockThread = new Thread(this);
        ClockThread.start();
        isRunning = true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        isRunning = false;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while (isRunning) {
                Thread.currentThread().sleep(1000);
                timer++;
                label.setText("逝去了" + timer);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        textThread2 textThread2 = new textThread2();
    }
}

其中关于Java AWT知识就不在这里介绍了,有兴趣的读者可以自己看看相关书籍。在本例中构建AWT窗体的应用程序方式是继承Frame类。采用第1种方式——继承方式实现线程体是不可以的,因为Java是单继承的,这个类不能既继承Frame又继承Thread。应该采用第2种方式——实现Runnable接口方式。Runnable接口也有一个run()方法,它是实现线程体方法,其代码处理与上一节是一样。需要注意的是,在第2种方法中,创建了一个Thread成员变量clockThread,才用构造方法new Thread(this)创建一个线程对象,其中创建线程使用的构造方法是Thread(Runnable target),其中的this就是代表本实例,它是一个实现了Runnable接口的实现类。

程序运行结果如图所示,屏幕开始加载的时候线程启动开始计算时间,1s更新一次UI,当单击“结束计时”按钮时,停止计时。

linux
相关资讯       Android多线程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款