一:线程
简单的来说:一个应用程序可以看成一个进程,比如QQ,PPS应用都是进程(当然,一个应用也可能有多个进程)。然后,在QQ应用中,可能有多个方法,比如,发送信息,接受信息,缓冲,播放,这些每一个具体的方法,都可以作为一个线程存在和使用。
二:Thread 类
继承Thread类:
class 类名称 extends Thread{ //继承Thread类
属性 ……;
方法 ……;
public void run(){ //覆写Thread类的run()方法
线程主体……;
}
}
但是在调用这个run()方法的时候,使用的是start()方法,这样,线程才会交替进行。
范例1:
package haizhu.com;
class MyThread extends Thread{
private String name;
public MyThread(String name){ //覆写构造方法
this.name = name;
}
public void run(){
//覆写run()方法
for(int i=0;i<10;i++){
System.out.println(this.name + i + "\t运行中");
}
}
}
public class MyThreadDemo {
public static void main(String args[]){
MyThread my1 = new MyThread("线程 A "); //创建对象线程A
MyThread my2 = new MyThread("线程 B "); //创建对象线程B
my1.start();
//使用start启动线程
my2.start();
}
}
可能的结果之一:
线程 A 0 运行中
线程 B 0 运行中
线程 B 1 运行中
线程 B 2 运行中
线程 A 1 运行中
线程 A 2 运行中
线程 B 3 运行中
线程 B 4 运行中
线程 B 5 运行中
线程 A 3 运行中
线程 B 6 运行中
线程 B 7 运行中
线程 B 8 运行中
线程 A 4 运行中
线程 A 5 运行中
线程 A 6 运行中
线程 A 7 运行中
线程 A 8 运行中
线程 A 9 运行中
线程 B 9 运行中
实现Runnable接口
class 类名称 implements Thread{ //实现Runnable接口
属性 ……;
方法 ……;
public void run(){ //覆写Thread类的run()方法
线程主体……;
}
}
范例2:
package haizhu.com;
class MyThread implements Runnable{
private String name;
public MyThread(String name){ //覆写构造方法
this.name = name;
}
public void run(){
//覆写run()方法
for(int i=0;i<10;i++){
System.out.println(this.name + i + "\t运行中");
}
}
}
public class MyThreadDemo {
public static void main(String args[]){
MyThread my1 = new MyThread("线程 A "); //创建对象线程A
MyThread my2 = new MyThread("线程 B "); //创建对象线程B
Thread t1 = new Thread(my1); //虽然实现
Runnable接口,但是启动线程的操作
Thread t2 = new Thread(my2); //还是依靠Thread
类的实例进行调用Thread类的start()方法
t1.start();
t2.start();
}
}
通过实现Runnable接口的方式进行多线程,但是启动线程的时候还是依靠Thread类的对象来实现。
在Thread类中提供了两个方法:public Thread(Runnable target) 和 public Thread(Runnable target, String name),这两个方法都可以接受Runnable的子类实例对象,所以依靠这个启动多线程。
四:Thread 和 Runnable 区别
使用Runnable可以实现资源的共享,但是如果继承Thread类则不行。