标签:
public void run()
Runnable
运行对象构造的,则调用该 Runnable
对象的 run
方法;否则,该方法不执行任何操作并返回。
Thread
的子类应该重写该方法。Runnable
的对象创建一个线程时,启动该线程将导致在独立执行的线程中调用对象的 run
方法。
run
的常规协定是,它可能执行任何所需的操作。package com.dashu.thread; public class DoSomething implements Runnable { private String name; public DoSomething(String name) { this.name = name; } public void run() { // TODO Auto-generated method stub for (int i = 0; i < 10; i++) { for (long k = 0; k < 100000000; k++) ; System.out.println(name + ": " + i); } } }
package com.dashu.thread; public class TestThread { public static void main(String[] args) { DoSomething do1 = new DoSomething("乌龟"); DoSomething do2 = new DoSomething("王八"); Thread t1 = new Thread(do1); Thread t2 = new Thread(do2); t1.start(); t2.start(); } }
2、扩展Thread类实现的多线程例子
package com.dashu.thread; public class TestThread extends Thread{ public TestThread(String name) { super(name); } public void run() { for(int i = 0;i<5;i++){ for(long k= 0; k <100000000;k++); System.out.println(this.getName()+" :"+i); } } public static void main(String[] args) { Thread t1 = new TestThread("王八"); Thread t2 = new TestThread("乌龟"); t1.start(); t2.start(); } }
执行的结果和方法一差不多。
标签:
原文地址:http://www.cnblogs.com/dashumeizi/p/4485404.html