使用Runnable接口创建多线程:
这是一个构造方法Thread(Runnable target)构造方法.Runnable接口中只有一个方法run()方法。当使用Thread(Runnable target)方法创建线程时,需为该方法传递一个实现 了Runnable接口的类对象中的run()方法作为其运行代码而不再调用Thread类中的run方法了
- public class ThreadDemo
- {
- public static void main(String args[])
- //new TestThread().start();
- TestThread tt=new TestThread();//创建TestThread类的一个实例
- Thread t= new TestThread();//创建一个Thread类的实例
- t.start();//使线程进入Runnable状态
- while(true)
- {
- System.out.println("main thread is running");
- }
- }
- }
- class TestThread implements Runnable//extends Thread
- {
- public void run()//线程的代码段,当执行start()里,线程开始执行
- {
- while(true)
- {
- System.out,println("Thread.currentThread().getName() is running");
- }
- }
- } /* 何问起 hovertree.com */
复制代码
|
|