线程分为两类:用户线程和守护线程(后台线程)
线程的状态:新建,就绪,运行,阻塞,死亡
创建线程有两种方法,一种是继承Thread类创建线程,另一种方法是通过实现Runnable接口而创建线程
继承Thread类创建线程一般步骤:
1.从Thread中派生一个类,并覆盖Thread中的run方法
2.创建该类的子对象
3.调用start方法驱动本线程
package com.thread.util;
class Mythread2 extends Thread {
public void run() {
int a = 10;
int b = 20;
int sum;
System.out.println(Thread.currentThread().getName() + "正在运行");
sum = a + b;
System.out.println("a+b=" + sum);
}
}
public class Mythread1 extends Thread {
public static int args = 10;
public static void main(String[] args) {
new Mythread1().start();
System.out.println("主线程正在运行");
new Mythread2().start();
}
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + "正在运行");
if (--args == 0)
return;
}
}
}
实现Runnable接口
由于java是单继承,所以当一个线程继承了其他类,就不能在继承Thread类了
故,java提供了第二种建立线程的方法,那就是实现Runnable接口产生线程。
接口Runnable只有一个方法run(),本方法传递一个实现了Runnable接口的类的对象
方法run()由系统自动调用,即通过start方法,而不能由程序调用
实现Runnable接口建立多线程的步骤:
1.定义一个类,实现Runnable接口。如:
public class Mythread implement Runnable{
public run(){...}}
2.创建自定义的类的对象,如MyThread target=new MyThread();
3.创建Thread类对象,并指定该类的对象作为target参数,如:
thread newThread=new thread();
4.启动线程
newThread。start();
/**
*
*/
package com.thread.util;
/**
* @author asus
*
*/
public class Mythread3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Target first,second;
first=new Target("第一个线程");
second =new Target("第二个线程");
Thread one,two;
one=new Thread(first);
two=new Thread(second);
one.start();
two.start();
}
}
class Target implements Runnable{
String s;
public Target(String s){
this.s=s;
System.out.println(s+"已经建立");
}
public void run(){
System.out.println(s+"已经运行");
try{Thread.sleep(1000);}catch(InterruptedException e){}
System.out.println(s+"已经结束");
}
}
运行结果:
第一个线程已经建立
第二个线程已经建立
第一个线程已经运行
第二个线程已经运行
第二个线程已经结束
第一个线程已经结束
使用Runnable接口创建线程的好处:
1.适合于多个相同程序代码的线程处理统一资源的情况
2.避免了单继承带来的局限性
3.有利于程序的健壮性,代码可被多个线程共享,代码与数据独立
4.几乎所有多线程应用都采用实现Runnable接口的方法