(1)start():作用是启动一个新的线程,新线程会执行线程中相应的run()方法,start()不能被重复调用,
(2)run():该方法和普通的成员方法一样,可以被重复调用。如果直接调用run()的话,会在当前线程中执行run(),而并不会启动新的线程。
示例代码:
- public class NewThread extends Thread{
- public NewThread(String name)
- {
- super(name);
- }
- public void run()
- {
- System.out.println(Thread.currentThread().getName()+" is running");
- }
- }
- public class Hello {
- public static void main(String [] args)
- {
- NewThread t1=new NewThread("thread1");
- System.out.println(Thread.currentThread().getName()+" running");
- t1.run();
- System.out.println(Thread.currentThread().getName()+" starting");
- t1.start();
- }
- }
运行结果:
main running
main is running
main starting
thread1 is running
Thread.currentThread().getName()是用于获取当前线程的名字,当前线程是指正在cpu中调度执行的线程。