黑马程序员_线程基础 (二)

2014-11-24 11:44:58 · 作者: · 浏览: 46
Thread类的run方法才能真正运行线程的代码

它创建线程的方法是:
1、将类声明为 Thread 的子类
2、该子类应重写 Thread 类的 run 方法
3、接下来可以分配并启动该子类的实例
下面的代码演示了如何使用Runnable接口来创建线程:
[java]
package com.debug.java;
public class ThreadDemo extends Thread{
/*
* 重写run方法
*/
@Override
public void run() {
super.run();
System.out.println(Thread.currentThread().getName());
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("main线程:"+Thread.currentThread().getName());
ThreadDemo thread1=new ThreadDemo();
ThreadDemo thread2=new ThreadDemo();
thread1.start();
thread2.start();
}
}

package com.debug.java;
public class ThreadDemo extends Thread{
/*
* 重写run方法
*/
@Override
public void run() {
super.run();
System.out.println(Thread.currentThread().getName());
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("main线程:"+Thread.currentThread().getName());
ThreadDemo thread1=new ThreadDemo();
ThreadDemo thread2=new ThreadDemo();
thread1.start();
thread2.start();
}
}输出:main线程:main
Thread-0
Thread-1 由于在建立线程时并未指定线程名,因此,所输出的线程名是系统的默认值,也就是Thread-n的形式
注意:任何一个Java程序都必须有一个主线程。一般这个主线程的名子为main。只有在程序中建立另外的线程,才能算是真正的多线程程序。也就是说,多线程程序必须拥有一个以上的线程。Thread类的start方法不能多次调用,如不能调用两次thread1.start()方法。否则会抛出一个IllegalThreadStateException异常。
Thread类有一个重载构造方法可以设置线程名。除了使用构造方法在建立线程时设置线程名,还可以使用Thread类的setName方法修改线程名。要想通过Thread类的构造方法来设置线程名,必须在Thread的子类中使用Thread类的public Thread(String name)构造方法,因此,必须在Thread的子类中也添加一个用于传入线程名的构造方法。下面的代码给出了一个设置线程名的例子:
[java]
package com.debug.java;

public class ThreadDemo extends Thread {

private String str;

public ThreadDemo(String str) {

this.str = str;
}

public ThreadDemo(String str, String threadName) {
super(threadName);
this.str = str;
}

/*
* 重写run方法
*/
@Override
public void run() {
super.run();
System.out.println(Thread.currentThread().getName());
}

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("main线程:" + Thread.currentThread().getName());
ThreadDemo thread1 = new ThreadDemo("thread1");
thread1.setName("thread1");
ThreadDemo thread2 = new ThreadDemo("thread2", "thread2");
ThreadDemo thread3 = new ThreadDemo("thread2", "thread2");
thread1.start();
thread2.start();
thread3.start();
}

}

package com.debug.java;

public class ThreadDemo extends Thread {

private String str;

public ThreadDemo(String str) {

this.str = str;
}

public ThreadDemo(String str, String threadName) {
super(threadName);
this.str = str;
}

/*
* 重写run方法
*/
@Override
public void run() {
super.run();
System.out.println(Thread.currentThread().getName());
}

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("main线程:" + Thread.currentThread().getName());
ThreadDemo thread1 = new ThreadDemo("thread1");
thread1.setName("thread1");
ThreadDemo thread2 = new ThreadDemo("thread2", "thread2");
ThreadDemo thread3 = new ThreadDemo("thread2", "thread2");
thread1.start();
thread2.start();
thread3.start();
}

}输出:main线程:main
thread1
th