java多线程在安卓应用开发中占据着重要的地位,一个应用程序到底性能如何与程序设计的架构,线程的设计有着密不可分的关系。
两种方法实现多线程
1、继承Thread类
2、实现runable接口
一、继承Thread类
Thread类的实现:
public class firstThread extends Thread {
private String name;
public firstThread(){
this.name = name;
}
public firstThread(String name){
this.name = name;
}
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println(this.name+i+"");
}
}
}
public class firstThread extends Thread {
private String name;
public firstThread(){
this.name = name;
}
public firstThread(String name){
this.name = name;
}
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println(this.name+i+"");
}
}
}
main函数中调用
</pre></p><p>执行结果</p><p>A 0A 1B0A 2A 3B1A 4B2B3B4B5B6A 5A 6A 7A 8A 9B7B8B9</p><p>可以看到程序不是顺序执行的,而是两个线程同时执行的,并且每次程序执行的结果都不一样。</p><p>注意:多线程程序的执行需要本地操作系统的支持,这里使用start而不是run,如果使用run,则是直接调用run函数,程序时顺序执行的,达不到多线程的效果。</p><p>二、实现runnable接口</p><p>类实现文件</p><p><pre name="code" class="java">public class hello implements Runnable{
private String name;
public hello()
{
}
public hello(String name)
{
this.name = name;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++)
{
System.out.println(name+""+i);
}
}
}
main文件
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
firstThread th1 = new firstThread("A");
firstThread th2 = new firstThread("B");
th1.start();
th2.start();
hello th3 = new hello("C");
hello th4 = new hello("D");
Thread demo1 = new Thread(th3);
Thread demo2 = new Thread(th4);
demo1.start(); //demo1 demo2多线程执行
demo2.start();
}
}
从执行结果可以看出,这四个线程 :th1 th2 demo1 demo2是同时执行的。
三、继承Thread和 实现runnable接口的区别
如果一个类继承Thread,则不适合资源共享;如果实现runnable接口,则很容易实现资源共享。
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源(比如多个线程公用一个资源:如剩余票数等,应该是多个线程共有的,但应该是static变量才会是多个线程共有的资源)
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。
因此建议使用runnable接口来实现,而不是用继承Thread类的方法。
/**
* @author Rollen-Holt
* 取得线程的名称
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
hello he = new hello();
new Thread(he,"A").start();
new Thread(he,"B").start();
new Thread(he).start();
}
}
【运行结果】:
A
A
A
B
B
B
Thread-0
Thread-0
Thread-0
说明如果我们没有指定名字的话,系统自动提供名字。
提醒一下大家:main方法其实也是一个线程。在java中所以的线程都是同时启动的,至于什么时候,哪个先执行,完全看谁先得到CPU的资源。
在java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用java命令执行一个类的时候,实际上都会启动一个JVM,每一个jVM实习在就是在操作系统中启动了一个进程。