一、线程的概念
1、线程是由表示程序运行状态的寄存器以及堆栈组成。
2、线程模型:一个虚拟CPU,该CPU执行的代码,代码所操作的数据。
二、线程的创建
1、方法一 :通过实现Runnable接口创建线程
优点:符合面向对象设计的思想;便于继承其他类。
其中Java.lang中的Runnable接口的定义:
Public interface Runnable{
Void run( );
}
创建步骤:
①定义一个类实现Runnable接口,即在该类中提供run()方法的实现;
②把Runnable的一个实例作为参数传递给Thread类的一个构造方法,该实例对象提供线程体run();
③调用Thread线程对象的start()方法启动线程。
一个简单的例子:
class Hello implements Runnable{
int i;
public void run(){
while(true){
System.out.println("hello"+i);
i++;
if(i==5)
break;
}
}
}
public class ThreadTest {
public static void main(String[] args){
Thread t= new Thread(new Hello());
t.start();
}
}
2、方法二:通过继承Thread类创建线程。
优点:程序代码简单,并可以在run()方法中直接调用线程的其他方法。
创建步骤:
①从Thread类派生子类,并重写run()方法定义线程体。
②创建该子类的对象创建线程。
一个简单的例子:
class Hello extends Thread{
int i;
public void run(){
while(true){
System.out.println("hello"+i);
i++;
if(i==5)
break;
}
}
}
public class ThreadTest {
public static void main(String[] args){
Hello2 t=new Hello2();
t1.start();
}
}
谢谢阅读。
1892

被折叠的 条评论
为什么被折叠?



