就是利用匿名内部类实现,补充下,做个笔记吧
- import java.util.Date;
- public class ThreadInnerClass {
- /**
- * @主要看使用内部类怎样实现一个线程
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- new Thread(new ThreadInner()).start();//相当于new Thread(实现Runnable接口)
- // new Thread(new ThreadInner(),"线程1").start();//同上,(取个名字)相当于new Thread(实现Runnable接口),ThreadInner对象操作线程
- // new ThreadInner().run();//线程也会运行,不过是这个main在操作线程。
- /*
- new Thread(new Runnable(){//相当于是实现runnable接口
- @Override
- public void run(){
- while(true)
- {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("1");
- }
- }
- }).start();
- */
- /*
- new Thread(){//直接重写run方法
- @Override
- public void run(){
- System.out.println("2");
- }
- }.start();
- */
- /*
- new ThreadInner2(){//相当于继承Thread,重写run方法。和上面直接重写run方法同理
- @Override
- public void run(){
- System.out.println("3");
- }
- }.start();
- */
- }
- }
- class ThreadInner implements Runnable{
- @Override
- public void run(){
- while(true)
- {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+" " + new Date());
- }
- }
- }
- class ThreadInner2 extends Thread{
- }