- package cn.itcast_11;
- /*
- * 匿名内部类的格式:
- * new 类名或者接口名() {
- * 重写方法;
- * };
- * 本质:是该类或者接口的子类对象。
- */
- public class ThreadDemo {
- public static void main(String[] args) {
- // 继承Thread类来实现多线程
- new Thread() {
- public void run() {
- for (int x = 0; x < 100; x++) {
- System.out.println(Thread.currentThread().getName() + ":"
- + x);
- }
- }
- }.start();
- // 实现Runnable接口来实现多线程
- new Thread(new Runnable() {
- @Override
- public void run() {
- for (int x = 0; x < 100; x++) {
- System.out.println(Thread.currentThread().getName() + ":"
- + x);
- }
- }
- }) {
- }.start();
- // 防面试,更有难度的(这里实现的是world,不会执行hellow)
- //这里其实是前两种的合并体
- new Thread(new Runnable() {
- @Override
- public void run() {
- for (int x = 0; x < 100; x++) {
- System.out.println("hello" + ":" + x);
- }
- }
- }) {
- public void run() {
- for (int x = 0; x < 100; x++) {
- System.out.println("world" + ":" + x);
- }
- }
- }.start();
- }
- }
复制代码
|
|