标签:
多线程:
线程的创建:
1.通过继承Thread类的类,重写run()方法:
工具:MyEclipse
1 /** 2 * 3 * @author Administrator 4 *继承Thread类 5 */ 6 public class Thread1 extends Thread{ 7 8 @Override 9 public void run() { 10 // TODO Auto-generated method stub 11 for(int i=0;i<10;i++){//方便举例:run()方法这里只打印10句Hello world和名字 12 System.out.println("Hello world!"+getName()); 13 } 14 } 15 16 }
1 public class Test { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 Thread1 a=new Thread1(); 9 a.setName("this is my name!");//通过Thread类的setName(),getName()方法的设置和得到名字,具体查看API帮助文档 10 a.start(); 11 } 12 13 }
运行的结果:
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
Hello world!this is my name!
2.编写一个实现Runnable接口的类:
1 /** 2 * 3 * @author Administrator 4 *实现Runnable接口 5 */ 6 public class Runnable1 implements Runnable{ 7 8 @Override 9 public void run() { 10 // TODO Auto-generated method stub 11 for(int i=0;i<10;i++){//方便举例:run()方法这里只打印10句Hello world和名字 12 System.out.println("Hello world!"+Thread.currentThread().getName());//Runnable接口中没有getName()方法,只有用Thread类的currentThread().getName()方法得到名字 13 } 14 } 15 }
1 public class Test { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 Runnable1 r=new Runnable1(); 9 Thread thread=new Thread(r); 10 thread.setName("This is a name!");//Runnable接口中没有setName()方法,使用Thread类 11 thread.start();//Runnable接口中没有start()方法,使用Thread类 12 } 13 14 }
1 public static void main(String[] args) { 2 // TODO Auto-generated method stub 3 new Thread(new Runnable1(),"This is a name").start();//这里用了匿名类的一种形式,结果和之前一样 4 5 6 7 } 8 9 }
1 public class Test { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 9 new Thread(new Runnable(){ 10 public void run(){ 11 for(int i=0;i<10;i++){//方便举例:run()方法这里只打印10句Hello world和名字 12 System.out.println("Hello world!"+Thread.currentThread().getName()); 13 } 14 } 15 },"This is a name!").start();//这里用了匿名类的一种形式,结果和之前的一样 16 17 } 18 19 }
运行的结果:
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
Hello world!This is a name!
实现Runnable的方式相对继承Thread类的方式优势:1.可以避免java单继承的局限;2.使用Runnable接口可以将虚拟Cpu(Thread类)与线程要完成的任务有效分离,更好的体现面向对象思想
标签:
原文地址:http://www.cnblogs.com/vencent-2016/p/5405973.html