读书人

线程的解说及范例

发布时间: 2012-11-25 11:44:31 作者: rapoo

线程的解说及实例

线程的用法:

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 < 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-0Thread-1 线程运行开始!0 Thread-11 Thread-11 Thread-02 Thread-02 Thread-13 Thread-03 Thread-14 Thread-04 Thread-15 Thread-06 Thread-05 Thread-17 Thread-08 Thread-06 Thread-19 Thread-07 Thread-1Thread-0 线程运行结束!8 Thread-19 Thread-1Thread-1 线程运行结束!说明:TestMitiThread1类通过实现Runnable接口,使得该类有了多线程类的特征。run()方法是多线程程序的一个约定。所有的多线程代码都在run方法里面。Thread类实际上也是实现了Runnable接口的类。在启动的多线程的时候,需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,然后调用Thread对象的start()方法来运行多线程代码。实际上所有的多线程代码都是通过运行Thread的start()方法来运行的。因此,不管是扩展Thread类还是实现Runnable接口来实现多线程,最终还是通过Thread的对象的API来控制线程的,熟悉Thread类的API是进行多线程编程的基础。---------------------------------------------------------?
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
?

读书人网 >Web前端

热点推荐