现在的位置: 首页 > 综合 > 正文

(1)传统线程技术回顾

2013年11月19日 ⁄ 综合 ⁄ 共 3901字 ⁄ 字号 评论关闭

1,java中线程的创建可以有两种方法:1、继承Thread类 2、实现Runnable接口

两者区别:

(1)、继承Thread类创建线程的方法, 在继承了Thread类之后, 不能再继承其他的方法, (在java中支持单继承),这样灵活性就不如实现Runnable接口来创建线程的方法了;

(2)、使用实现Runnable接口来创建线程可以达到资源共享!(继承Thread类创建线程也可以实现资源共享,但是比较的麻烦。)

在我们创建线程的时候都会优先采用实现Runnable接口的方法。

package com.thread;

public class TestThread2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Runner r = new Runner();
		r.start();
		
		for(int i=0; i<100; i++) {
			System.out.println("Main Thread:------" + i);
		}
	}

}
class Runner extends Thread {
	public void run() {
		for(int i=0; i<100; i++) {	
			System.out.println("Runner1 :" + i);
		}
	}
}
package com.thread;

public class TestThread3 {

	/** 优先考虑的方式。
	 * @param args
	 */
	public static void main(String[] args) {
		Runner2 r = new Runner2();
		Thread t1 = new Thread(r);
		Thread t2 = new Thread(r);
		t1.start();
		t2.start();
	}
}

class Runner2 implements Runnable{

	@Override
	public void run() {
		for(int i=0;i<30;i++){
			System.out.println("No:" + i);
		}
		
	}
	
}




package com.itm.thread;

public class TraditionalThread {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			Thread thread = new Thread() {
				@Override
				public void run() {
					while(true){
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println("1  " + Thread.currentThread().getName());
						System.out.println("2  " + this.getName());
					}
				}
			};
			thread.start();
			
			
			Thread thread2 = new Thread(new Runnable(){
				@Override
				public void run() {
					while(true){
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println("1  " + Thread.currentThread().getName());
						// this 就不代表线程了。因为在 Runnable 对象里面。
//						System.out.println("2" + this.getName());
					}
					
				}
			});
			thread2.start();
			
/********************************************************************************
 * 
 * 注释源码说明:利用了  面向对象的  覆盖技术。
 * 
 * 
 * 调用 start()方法,start()方法 会找  当前对象的run()方法 
 * (1) 如果自己没有 就找父类中的run()方法。
 * 			父类的run()方法 会找 Runnable。
 * (2) 如果 自己有 run()方法,就把 父类的覆盖了。
 * 
 * 
 */
			
			new Thread(
					new Runnable() {
						
						@Override
						public void run() {
							while(true){
								try {
									Thread.sleep(500);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								System.out.println("Runnable :" + Thread.currentThread().getName());
							}							
						}
					}
			){
				public void run() {
					while(true){
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println("Thread :  " + Thread.currentThread().getName());
					}
				};
			}.start();
			
	}
	
}

关于 上面注释源码的:

(1):
public void run() {
	if (target != null) { // 如果 target不是为空 就会执行 Runnable的run(); 因为:target是 Runnable的 一个变量。
	    target.run();
	}
}

(2) :  
			/* What will be run. */
    	private Runnable target;


	------------------------------------------------------------------------------------------------------


	 /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
	Thread parent = currentThread();
	SecurityManager security = System.getSecurityManager();
	if (g == null) {
	    /* Determine if it's an applet or not */
	    
	    /* If there is a security manager, ask the security manager
	       what to do. */
	    if (security != null) {
		g = security.getThreadGroup();
	    }

	    /* If the security doesn't have a strong opinion of the matter
	       use the parent thread group. */
	    if (g == null) {
		g = parent.getThreadGroup();
	    }
	}

	/* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
	g.checkAccess();

	/*
	 * Do we have the required permissions?
	 */
	if (security != null) {
	    if (isCCLOverridden(getClass())) {
	        security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
	    }
	}


        g.addUnstarted();

	this.group = g;
	this.daemon = parent.isDaemon();
	this.priority = parent.getPriority();
	this.name = name.toCharArray();
	if (security == null || isCCLOverridden(parent.getClass()))
	    this.contextClassLoader = parent.getContextClassLoader();
	else
	    this.contextClassLoader = parent.contextClassLoader;
	this.inheritedAccessControlContext = AccessController.getContext();
	this.target = target;
	setPriority(priority);
        if (parent.inheritableThreadLocals != null)
	    this.inheritableThreadLocals =
		ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

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



抱歉!评论已关闭.