JAVA初步认识线程

       在JAVA实现中线程,有2中方法,一种是继承Thread类,一种是实现Runnable接口。

1.继承Thread类

      如果子类继承了Thread类,则子类必须覆盖Thread类中的run方法,次方法是线程的主体。

package thread;

public class MyThread extends Thread{

	private String name;
	public MyThread(String name){
		this.name=name;
	}
	@Override
	public void run(){
		for(int i=1;i<=5;i++){
			System.out.println(name+" i="+i);
		}
	}
}

测试类

<span style="font-size:18px;">package thread;

public class ThreadClient {
	public static void main(String[] args) {
		MyThread t1=new MyThread("线程A  ");
		MyThread t2=new MyThread("线程B  ");
		t1.start();//启动线程A
		t2.start();//启动线程B
	}
}
</span>

运行结果

线程A   i=1
线程A   i=2
线程A   i=3
线程A   i=4
线程A   i=5
线程B   i=1
线程B   i=2
线程B   i=3
线程B   i=4
线程B   i=5


     接下来,简单浏览下Thread类的源码,看看为什么子类必须要覆盖父类(Thread类)的run方法。

Thread类的定义如下

public class Thread implements Runnable 

    它实现了Runnable接口,在来看看 Runnable接口里面有什么。

public abstract void run();

     所以Thread类中必定会有run方法。那再来看看Thread类中的run方法

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


     发现如果target!=null,它调用的是target中的run方法。那这个target又是哪来的。再看了下代码,发现Thread类有好几个构造方法,但是这些构造方法都会调用init()方法进行初始化.

public Thread(String name) {
	init(null, null, name, 0);
    }

private void init(ThreadGroup g, Runnable target, String name,long stackSize) 

     看到target是外部传进来的,并且是Runnable的实现类,而Thread也实现了Runnable接口,这让我想起了java的静态代理,Thread相当于代理类,而传给Thread的target(实现了Runnable的实现类)相当于委托类.

     看到这,应该明白了,使用继承Thread实现线程的话,必须要覆盖Thead类的run方法的原因了(启动线程使用start()方法,start方法调用本地方法start0(),最终会调用到run()方法,如果子类不覆盖Thread类的run()方法的话,线程会直接调用Thread类的run()方法,而此时target==null,所以相当于什么都不做)。

      在这看不明白的run()是在哪被调用执行的话,拉到后面,后面贴源码,一步一步跟踪来看。

2.实现Runnable接口

       上面说道了Thread类相当于静态代理中的代理类,既然这样那就可以创建了一个业务类(目标类,委托类)并且实现Runnable接口,传给Thread类就OK了。

package thread;

public class MyThread implements Runnable{

	@Override
	public void run(){
		for(int i=1;i<=5;i++){
			System.out.println(Thread.currentThread().getName()+" i="+i);
		}
	}
}
package thread;

public class ThreadClient {
	public static void main(String[] args) {
		new Thread(new MyThread(),"线程A ").start();//启动线程A
		new Thread(new MyThread(),"线程B ").start();//启动线程B
	}
}

运行结果

线程A  i=1
线程A  i=2
线程A  i=3
线程A  i=4
线程A  i=5
线程B  i=1
线程B  i=2
线程B  i=3
线程B  i=4
线程B  i=5

    

 

     这2中方法都可以实现线程,但是推荐大家使用实现Runnable接口。

    实现Runnable接口相对于继承Thread类有如下优势

    (1)适合多个相同程序代码的线程去处理同一资源的情况。

    (2)可以避免JAVA中单继承特性带来的局限性。

    (3)增强了程序的健壮性,代码能被多个线程共用,代码和数据是独立的。


 

    只要第二点的优势就不多说了,第1,3点,下面写个小程序看一下就OK了。

package thread;

public class MyThread  extends Thread{
    private int ticket=5;
    private String name;
    public MyThread(String name){
    	this.name=name;
    }
	@Override
	public void run(){
		for(int i=1;i<=10;i++){
			if(ticket>0)
			  System.out.println(name+"卖出票 "+(ticket--));
		}
	}
}



package thread;

public class ThreadClient {
	public static void main(String[] args) {
		MyThread t1=new MyThread("售票员A ");
		MyThread t2=new MyThread("售票员B ");
		t1.start();
		t2.start();
	}
}

运行结果
售票员A 卖出票 5
售票员A 卖出票 4
售票员A 卖出票 3
售票员A 卖出票 2
售票员A 卖出票 1
售票员B 卖出票 5
售票员B 卖出票 4
售票员B 卖出票 3
售票员B 卖出票 2
售票员B 卖出票 1

 

    发现售票员A和售票员B都各自出售了5张票。

package thread;

public class MyThread  implements Runnable{
    private int ticket=5;
   
	@Override
	public void run(){
		for(int i=1;i<=10;i++){
			if(ticket>0)
			  System.out.println(Thread.currentThread().getName()+"卖出票 "+(ticket--));
		}
	}
}



package thread;

public class ThreadClient {
	public static void main(String[] args) {
		MyThread myThread=new MyThread();
		new Thread(myThread,"售票员A ").start();
		new Thread(myThread,"售票员B ").start();
	}
}

运行结果

售票员B 卖出票 5
售票员B 卖出票 4
售票员B 卖出票 3
售票员B 卖出票 2
售票员B 卖出票 1


3.start()之后run()是如何被调用的

     看下源代码就发现,其实很简单,这里也不多说,直接贴源码。

     当你new Thread(new MyThread(),"线程A ")时,看Thread类中的构造方法,发现都会掉要一个init()方法

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

 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();
    }

重点留意target这个参数,下面有用,发现target对象其实就是你写的类(它可能是实现了接口Runnable或继承了Thread,Thread其实也实现了接口Runnable)。

    接着看,我们写的代码中,调用了start()方法,看看start()方法做了什么。

/**
     * Causes this thread to begin execution; the Java Virtual Machine 
     * calls the <code>run</code> method of this thread. 
     * <p>
     * The result is that two threads are running concurrently: the 
     * current thread (which returns from the call to the 
     * <code>start</code> method) and the other thread (which executes its 
     * <code>run</code> method). 
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    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();
        group.add(this);
        start0();
        if (stopBeforeStart) {
	    stop0(throwableFromStop);
	}
    }

    private native void start0();

    /**
     * If this thread was constructed using a separate 
     * <code>Runnable</code> run object, then that 
     * <code>Runnable</code> object's <code>run</code> method is called; 
     * otherwise, this method does nothing and returns. 
     * <p>
     * Subclasses of <code>Thread</code> should override this method. 
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    public void run() {
	if (target != null) {
	    target.run();
	}
    }

   看上面方法,start()调用了start0().然后start0()就看不到任何代码了,有些同学就看不明白了,那我重写的run()方法呢,谁来调用了,为什么它会被执行了?呵呵,别急,大家看看start()方法上面的注释,看到这注释,哦,原来是执行start0()时,会启动一个子线程,这个子线程会去执行Thread类中的run()方法,也就是说Thread类中的run()是子线程执行,主线程(可以理解为上面main方法所在那个线程为主线程)没执行。再看Thread类中的run()方法,发现如果target!=null它就执行target对象中的run()方法,再回头看看,上面说了,target 对象,就是你自己写的那个对象(它实现了Runnable接口或继承了Thread类),target.run()就是你重写的那个run()方法。

     嗯,上面的说法有一点不严谨,就是如果MyThread是继承Thread类的,那MyThread类中的run()已经覆盖了父类Thread中的run()方法了。


 
 
 
 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值