首页 > 编程语言 > 详细

java线程的实现

时间:2015-11-03 00:52:29      阅读:336      评论:0      收藏:0      [点我收藏+]

    

1.进程与线程

    进程是程序的一次动态执行过程,它经历了从代码加载、执行到执行完毕的一个完整过程。

    多进程操作系统能同时运行多个进程(程序),由于CPU具备分时机制,所以每个进程都能循环获得自己的CPU时间片。由于CPU执行速度非常快,使得所有程序好像在"同时"运行。

    线程是在进程基础上的进行进一步划分。多线程是指一个进程在执行过程中可以产生多个线程,这些线程可以同时存在、同时运行。

    多线程机制可以同时运行多个程序块,当有线程包含耗时操作(如循环),可以让另一个线程做其他的处理。传统程序语言一次只能运行一个程序块,遇到耗时操作只能按顺序执行完耗操作才能继续执行程序。

    

2.java中线程的实现

①继承Thread类

语法

class 类名称 extends Thread {    //继承Thread类
	属性...;                //类中定义属性
	方法...;                 //类中定义方法
	public void run() {        //覆写Thread类中的run()方法,此方法是线程的主体
	    //线程主体
	}
}

示例:

ThreadDemo.java  

class MyThread extends Thread {
	private String name;

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(name + "运行,i= " + i);
		}
	}
}

public class ThreadDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程A");
		mt1.start();
		mt2.start();
	}

}

    注:使用start()方法启动多线程而不用run()方法启动线程的原因。

    start()方法调用start0()方法,start0()方法使用native关键字声明,说明启动多线程的实现需要依靠底层操作系统支持。

    继承Thread类实现多线程,同一线程类对象只能调用一次start()方法,调用多次会出抛出IllegaIlThreadStateException异常。

源码:

 public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group‘s list of threads
         * and the group‘s unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();


    

②实现Runnable接口

语法:    

class 类名称 implements Runnable{    //实现Runnable接口
	属性...;                //类中定义属性
	方法...;                 //类中定义方法
	public void run() {        //覆写Runnable接口中的run()方法
	    //线程主体
	}
}

示例:

RunnableDemo.java 

class MyThread01 extends Thread {
	private String name;

	public MyThread01(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(name + "运行,i= " + i);
		}
	}
}

public class RunnableDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程A");
		Thread t1 = new Thread(mt1);
		Thread t2 = new Thread(mt2);
		t1.start();
		t2.start();
	}

}

    启动线程需要Thread类中的start()方法,Thread类中的run()方法调用的是Runnable接口中的run()方法,此方法由Runnable子类完成,所以如果通过继承Thread类实现多线程,则必须覆写run()方法。

    Thread类中的构造函数接受Runnable的子类,所以可以通过Thread类来启动该线程。

源码:

private Runnable target;
public Thread(Runnable target,String name){
    init(null,target,name,0);
}
...

public void run(){
    if(target != null){
        target.run();
    }
}

    


使用Runnable接口实现多线程可以避免由于java的单继承带来的局限。

注:


1.java为什么不支持多继承

多继承主要是因为很多同名方法,或者是同名属性容易记混,但是接口,是对方法的重写,而且是一个接口往往有一个特定的方法,虽然方法是一样的,但是可以通过接口的不同来区分。



本文出自 “人生若只如初见” 博客,请务必保留此出处http://9944522.blog.51cto.com/9934522/1708932

java线程的实现

原文:http://9944522.blog.51cto.com/9934522/1708932

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!