- package cn.itcast.heima;
- public class TraditionalThread {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName());
- }
- }
- };
- thread.start();
- Thread thread2=new Thread(new Runnable(){
- @Override
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName());
- }
- }
- });
- thread2.start(); //让第二个线程也运行,则他就执行Thread()内部的run()方法。
- new Thread( new Runnable(){
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("runnable:" Thread.currentThread().getName());
- }
- };
- }
- ){
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Thread:" Thread.currentThread().getName());
- }
- };
- }.start();
- }
- }
创建线程的两种方式:
1.在Thread子类覆盖的run方法中编写运行代码
2.在传递给Thread对象的Runnable对象的run方法中编写代码
总结
查看Thread类的run()方法的源码,可以看到其实这两种方式都是在调用Thread对象的run()方法,如果Thread类的run()方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run()方法。
阅读(999) | 评论(0) | 转发(0) |