线程是程序中一个单一的顺序控制流程.在单个程序中同时运行多个线程完成不同的工作,称为多线程.
线程和进程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器为其执行上下文.多线程主要是为了节约cpu时间,发挥利用,根据具体情况而定. 线程的运行中需要使用计算机的内存资源和cpu
线程的周期
新建 就绪 运行 阻塞 死亡
线程调度与优先级
有线程进入了就绪状态,需要有线程调度程序来决定何时执行,根据优先级来调度.
线程组
每个线程都是一个线程组的一个成员,线程组把多个线程集成一个对象,通过线程组可以同时对其中的多个线程进行操作.在生成线程时必须将线程放在指定的线程组,也可以放在缺省的线程组中,缺省的就是生成该线程的线程所在的线程组.一旦一个线程加入了某个线程组,不能被移出这个组.
守护线程
是特殊的线程,一般用于在后台为其他线程提供服务.
isdaemon():判断一个线程是否为守护线程.
set daemon():设置一个线程为守护线程.
thread类和runnable接口
thread类
类thread在包java.lang中定义,它的构造方法如下:
public thread();
public thread(runnable target);
public thread(runnable target,string name);
public thread(string name);
public thread(threadgroup group,runnable target);
public thread(threadgroup group, string name);
主要方法
isactive() 判断是否处于执行状态
suspend() 暂停执行
resume 恢复执行
start() 开始执行
stop() 停止执行
sleep() 睡眠
run() 程序体
yield() 向其他线程退让运行权
线程优先级
public statuc final int max_priority最高优先级,10
public statuc final int min_priority最低优先级,1
public statuc final int norm_priority普通优先级,5
runnable接口
runnable接口中只定义了一个方法run()作为线程体,
void run()
java的线程是通过java.lang.thread类来实现的。
vm启动时会有一个由主方法(public static void main(){})所定义的线程。
可以通过创建thread的实例来创建新的线程。
每个线程都是通过某个特定的thread对象所对应的方法run()来完成其操作的,方法run()称为线程体。
通过调用thread类的start()方法来启动一个线程
java里面实现多线程,有2个方法
1 继承 thread类,比如
class mythread extends thread {
public void run() {
// 这里写上线程的内容
}
public static void main(string[] args) {
// 使用这个方法启动一个线程
new mythread().start();
}
}
2 实现 runnable接口
class mythread implements runnable{
public void run() {
// 这里写上线程的内容
}
public static void main(string[] args) {
// 使用这个方法启动一个线程
new thread(new mythread()).start();
}
}
一般鼓励使用第二种方法,应为java里面只允许单一继承,但允许实现多个接口。第二个方法更加灵活。
http://www.bkjia.com/phpjc/771954.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/771954.htmltecharticle是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点在运行中必不可少的资源,但它可与同...
