---
title: "重拾java之线程1"
author: "sam406"
date: "2012-09-10T00:17:12Z"
tags: []
categories: ["编程语言"]
slug: "java-1"
draft: false
lastmod: "2013-03-24T09:29:59Z"
id: 1674737
url: "https://sam406.iteye.com/blog/1674737"
---

接触java也有一段时间了，以前选择java原因就是java很流行，好就业，那是开始学习java只是简单学习，没有更深层的理解how ,why。这也是觉得自己的java技术还是这么菜。现在开始重温下j2se方面的知识，写点笔记记录下
     概念
   线程，就是你写的一个简单的程序，运行的载体的就是线程，帮你完成一件事。我的简单理解就是，线程就像洗衣机一样，它的功能帮你完成洗衣服，犹豫你很懒堆了一个月的衣服，而此时要洗，肯定是一个洗衣机搞不定了哦，而你要赶时间要把这个一个衣服用最短的时间洗完，你就用多台洗衣机来洗（纯属假设，如果你家是卖洗衣机的到可试试），刚才那情形就是传说的多线程，就是多个任务同时运行，并起运行，就是并发了。
     运行
   你要用洗衣机洗衣服，前提是你已有脏衣服的存在，放在洗衣机里，然后插上电，打开洗衣开关，洗衣机就开始工作了哦。同样在使用线程时，你要把你要打算做的事要事先编码好，然后把它添加到线程的run()方法中。最后调用start()方法，ok! 跟洗衣机一样工作了。随着高科技和不断创新的发展，洗衣机洗衣方式也是多种多样，我见过两种，一种是很古老的：就是洗衣和脱水时分开的那种，这种用起来很不方便，需要自己脱水（我很讨厌这种洗发）。一种是很先进的：就是洗衣和脱水完美的融为一体，这样很方便了，不要你亲自来脱水（很喜欢这种洗发）。其实实现线程的方式也有两种了。第一种就是很直接的使用Thread类搞定。继承Thread 在run()方法中放入你要实现的功能。如下代码


```java
 public class ThreadDemo extends Thread {

	@Override
	public void run() {
     System.out.println("hello ! i'm from Thread");
	}

}
```

在run方法中只是一句简单的输出语句。然后运行，代码如下

```java
 public static void main(String [] args){
	 ThreadDemo demo=new ThreadDemo();
	                   demo.start();
  }
```


好了第一种线程运行方式搞定，接下来看第二种，就是实现Runnable接口了

```java
public class ThreadDemo2  implements Runnable{

	@Override
	public void run() {
		  System.out.println("hello ! i'm from Runnable");
		
	}
 
}
  
```

这种方式就是逼着你要实现run()方法了。其执行也略有不同了

```java
public static void main(String [] args){
	Thread demo=new Thread(new ThreadDemo2());
	demo.start();
}

```

实现Runnable执行需要一个载体了，为什么了？看Runnable的源码

```java
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     * 
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
} 
```
   

看起来是不是感觉so easy!它就一个run()方法，就是有装任务的地方，就是没发让功能执行，所以需要求助外援了（纯属简单理解，写的不够严谨）。但为什么要选Thread了，这要看源码了

```java
public  class Thread implements Runnable {
............
}
```

 
看到没，Thread 也实现了Runnable，看来他们有父子之情呀，从面向对象世界来说，子原则上都比父功能更强大丰富（现实中父子谁强谁弱这就无比复杂了，还是面向对象世界单纯）。
所以子要继承父的所有功能，看Thread如何实现，上源码

```java

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
```

这个构造方法是传入一个Runnable类型参数，然后在传个init方法，init方法就是Thread类的初始化的地方，其中有一条语句很重要
 
```java
 this.target = target;
```

 就是把传入Runnable 类型参数赋给Thread成员变量target，疑问来了，就是在前面实例化了继承Thread类的对象，它的构造方法就是一个无参的构造函数，在看源码

```java
   public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
```

在这个构造方法中给init方法传入的第二个参数是null，也就是target=null,初始化了一个null的target,是不是很疑惑呀。好，在上源码

```java


    /**
     * 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)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

```

这是从写了Runnable的run()方法，这里面就一个片段，意思是如果target不为null，也就是说我们传入了一个Runnable对象，然后调用Runnable对象的run()方法,这样是因为我们已在实现Runnable接口的类中以从写了run()方法，如果target为null，意思就是通过new Thread而不传入Runnable对象，然后就会调用继承了Thread类的实现类中的run()方法。

  在一个循环中创建线程多次运行可能会产生不同的结果，主要是线程调度机制是非确定性的。