什么是多线程?这些话就不说了,直接看例子。
package com.ztz.myThread; public class MyThread extends Thread{ @Override public void run() { System.out.println("继承Thread"); } public static void main(String[] args)throws Exception { MyThread t=new MyThread(); t.start(); } }
package com.ztz.myThread; public class MyRunnable implements Runnable{ @Override public void run() { System.out.println("实现Runnable接口"); } public static void main(String[] args)throws Exception { MyRunnable runnable=new MyRunnable(); Thread thread=new Thread(runnable); thread.start(); } }
package com.ztz.myThread; public class MyThread{ public static void main(String[] args)throws Exception { System.out.println(Thread.currentThread().getName()); } }运行该方法,控制台输出:
package com.ztz.myThread; public class MyThread extends Thread{ public MyThread() { System.out.println("构造方法:"+Thread.currentThread().getName()); } @Override public void run() { System.out.println("run:"+Thread.currentThread().getName()); } public static void main(String[] args)throws Exception { MyThread thread=new MyThread(); thread.start(); } }运行该方法控制台输出:
package com.ztz.myThread; public class MyThread extends Thread{ @Override public void run() { try{ System.out.println("run start:"+System.currentTimeMillis()); Thread.sleep(2000); System.out.println("run end:"+System.currentTimeMillis()); }catch(Exception e){ } } public static void main(String[] args)throws Exception { MyThread thread=new MyThread(); System.out.println("thread start:"+System.currentTimeMillis()); thread.start(); System.out.println("thread end:"+System.currentTimeMillis()); } }
package com.ztz.myThread; public class MyThread{ public static void main(String[] args)throws Exception { Thread currentThread = Thread.currentThread(); System.out.println(currentThread.getName()+"--->"+currentThread.getId()); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/luckey_zh/article/details/46946551