传统创建线程的两种方式
package cn.itcast.heima2; public class TraditionalThread { public static void main(String[] args) { // TODO Auto-generated method stub Thread thread = new Thread() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); System.out.println(this.getName()); } } }; thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } } }); thread2.start();//更可以体现面向对象的思想,线程和代码隔离 new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("runnable:"+Thread.currentThread().getName()); } } }){ @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("thread:"+Thread.currentThread().getName()); } } }.start(); } }
时间: 2024-10-27 07:55:26