---
title: "线程的解说及实例"
author: "duyunfengsolo"
date: "2009-09-19T13:57:01Z"
tags: ["thread"]
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2011-11-20T13:05:11Z"
id: 472028
url: "https://solodu.iteye.com/blog/472028"
---

线程的用法：

1\. 继承Thread类，一定要覆盖run方法，代码都写到run方法里面。

2\. 实现Runnable接口(java.lang)，接口中有run方法。

 

Thread.currentThread.getName()方法和this.getName()方法的区别：

    只有在一个类继承了Thread类时，这两个方法才能通用，因为只有Thread类中才有getName()方法，而如果当一个类去实现Runnable接口时，则不能用this.getName()方法，因为它不是Thread类的子类。

 

\--------------------------------------------------------

public class TestMitiThread1 implements Runnable {

 

    public static void main(String\[] args) {

        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");

        TestMitiThread1 test = new TestMitiThread1();

        Thread thread1 = new Thread(test);

        Thread thread2 = new Thread(test);

        thread1.start();

        thread2.start();

        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");

    }

 

    public void run() {

        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");

        for (int i = 0; i &lt; 10; i++) {

            System.out.println(i + " " + Thread.currentThread().getName());

            try {

                Thread.sleep((int) Math.random() * 10);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");

    }

}

结果:

main 线程运行开始!

Thread-0 线程运行开始!

main 线程运行结束!

0 Thread-0

Thread-1 线程运行开始!

0 Thread-1

1 Thread-1

1 Thread-0

2 Thread-0

2 Thread-1

3 Thread-0

3 Thread-1

4 Thread-0

4 Thread-1

5 Thread-0

6 Thread-0

5 Thread-1

7 Thread-0

8 Thread-0

6 Thread-1

9 Thread-0

7 Thread-1

Thread-0 线程运行结束!

8 Thread-1

9 Thread-1

Thread-1 线程运行结束!

说明：

TestMitiThread1类通过实现Runnable接口，使得该类有了多线程类的特征。run（）方法是多线程程序的一个约定。所有的多线程代码都在run方法里面。Thread类实际上也是实现了Runnable接口的类。

在启动的多线程的时候，需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象，然后调用Thread对象的start()方法来运行多线程代码。

实际上所有的多线程代码都是通过运行Thread的start()方法来运行的。因此，不管是扩展Thread类还是实现Runnable接口来实现多线程，最终还是通过Thread的对象的API来控制线程的，熟悉Thread类的API是进行多线程编程的基础。

\---------------------------------------------------------------------------------------------

 

```
public class MyThread extends Thread{
	public int x = 0;
	public void run(){
		System.out.println(++x);
	}
	
	public static void main(String[] args) {
		for(int i=0;i<10;i++){
			Thread t = new MyThread();
			t.start();
		}
	}
}
结果: 10个1.......1......1
```

 

```
public class TaThread implements Runnable{
	public int x = 0;
	public void run(){
		System.out.println(++x);
	}
	
	public static void main(String[] args) {
		for(int i=0;i<10;i++){
			TaThread ta = new TaThread();
			Thread t = new Thread(ta);
			t.start();
		}
	}
}
结果: 从1到10.  1..5....10
```