什么是线程?
在操作系统中,通常将进程看作系统资源的分配单位和独立运行的基本单位。一个任务就是一个进程。线程是比进程更小的·执行单位。那什么是线程呢,线程是比进程更小的执行单位,是程序执行流的最小单位。一个标准的线程由线程ID、当前指令指针PC、寄存器集合和堆栈组成。另外线程是进程中的一个实体,是被系统独立调度和分配的基本单位,线程自己不拥有系统资源,只拥有运行中必不可少的资源。
线程的基本状态:就绪、阻塞、运行、新建、死亡。
java多线程的实现
在java中有两种方式可以创建线程:一种继承Thread类;另一种是实现Runnable接口。
1.Thread类
Thread类是一种具体的类,即不是抽象类,该类封装了线程的行为。利用Thread类创建一个线程,必须创建一个从Thread一个Thread类导出的新的子类。必须覆盖thread的run()方法来完成线程业务工作。当启动线程时必须调用线程的start()函数。
package com.lzw;
class My_Thread extends Thread{
/**
* 线程的实现: 继承Thread
*/
private int count=0; //定义一个静态变量,所有的线程对象共享
public void run(){ //覆盖run方法,实现自己的功能
int i;
for(i=0;i<3;i++){
count=count+1;
System.out.println("My Name is"+ getName()+"count="+count);
try{ //休息10毫秒,让其他线程有机会进行
sleep(1);
}catch(InterruptedException e){
}
}
}
public My_Thread(String name){ //构造方法
super(name);
}
}
public class MyThread{
public static void main(String srgs[]){
My_Thread trFrist,trSecond;
trFrist=new My_Thread("frist Thread");
trSecond=new My_Thread("second Thread");
//启动两个线程
trFrist.start();
trSecond.start();
}
}
2.Runnable接口
在实际java程序开发中,我们更倾向于通过Runable接口实现多线程,因为实现Runnable接口相比继承Thread类而言,既可以避免单继承的局限,也可以避免类层次的加深,同时更适合资源的共享。
package com.lzw;
public class RunableText {
/**
* @实现Runable接口 要实现run()
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadRunable trFrist,trSecond;
trFrist=new ThreadRunable("frist Thread");
trSecond=new ThreadRunable("second Thread");
//启动两个线程
trFrist.start();
trSecond.start();
}
}
class ThreadRunable implements Runnable{
private static int count=0;
private Thread trval;
public void run() {
// TODO Auto-generated method stub
int i=0;
for(i=0;i<3;i++){
count++;
System.out.println("My Name is"+ trval.getName()+"count="+count);
try{ //休息10毫秒,让其他线程有机会进行
trval.sleep(10);
}catch(InterruptedException e){
}
}
}
public ThreadRunable(String name){
trval=new Thread(this,name);
}
public void start(){
trval.start();
}
}