Java新建线程的3种方法

Java新建线程的3种方法

===================

Java创建线程有3种方法:
(1)继承Thread;
(2)实现Runnable接口;
(3)实现Callable接口;

附加:匿名内部类;

由于Java只支持单继承,所以用继承的方式创建线程,比较死板,不够灵活;用实现接口的方式创建线程,可以实现多个接口,比较灵活。
Runnable和Callable接口的区别:
(1)Callable重写的方法是call(),Runnable重写的方法是run();
(2)Callable的任务执行后可返回值,而Runnable不能返回值;
(3)call方法可以抛出异常,run()不可以;
(4)运行Callable任务可以拿到一个future对象,表示异步计算的结果,
它供检查计算是否完成的方法,以等待计算完成,并检索计算的结果。通过Future对象可以了解任务的执行情况,可取消任务的执行,还可以获取执行的结果。

1.继承Thread

package com.java.thread;

 

public class ThreadClient {

 

public static void main(String[] args) {

Print p1 = new Print();

Print p2 = new Print();

p1.start();

p2.start();

 

}

 

}

 

class Print extends Thread{

@Override

public void run(){

for(int i=0;i<10;i++){

System.out.println(Thread.currentThread().getName()+":"+i);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

 

2.实现Runnable接口

package com.java.thread;

 

public class ThreadClient1 {

 

public static void main(String[] args) {

Runnable p1 = new Salesman("Jack");

Runnable p2 = new Salesman("Iris");

 

Thread t1 = new Thread(p1);

Thread t2 = new Thread(p2);

 

t1.start();

t2.start();

}

 

}

 

class Salesman implements Runnable{

 

private int ticket=100;//每个线程都拥有100张票

    private String name;

    Salesman(String name){

        this.name=name;

    }

    

@Override

public void run(){

        while(ticket>0){

         System.out.println(ticket--+" is saled by "+name+","+Thread.currentThread().getName());

        try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

     }

}

 

}

3.实现Callable接口

package com.java.thread;

 

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

 

public class CallType {

 

public static void main(String[] args) {

ExecutorService es = Executors.newCachedThreadPool();

List<Future<String>> results = new ArrayList<Future<String>>();

for(int i=0;i<5;i++){

results.add(es.submit(new TaskWithResult(i)));

}

 

for(Future<String> fs : results){

try {

System.out.println(fs.get());

} catch (InterruptedException | ExecutionException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

 

class TaskWithResult implements Callable<String>{

private int id;

public TaskWithResult(int id){

this.id = id;

}

@Override

public String call() throws Exception {

return "result of TaskWithResult" + id;

}

}

 

4.匿名内部类:

new Thread(new Runnable() { @Overridepublicvoidrun() { for (int x = 0; x < 100; x++) { System.out.println("hello" + ":" + x); } } }) { publicvoidrun() { for (int x = 0; x < 100; x++) { System.out.println("world" + ":" + x); } } }.start();

 

1.继承Thread

 

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. public class ThreadClient {  
  4.   
  5.     public static void main(String[] args) {  
  6.         Print p1 = new Print();  
  7.         Print p2 = new Print();  
  8.         p1.start();  
  9.         p2.start();  
  10.   
  11.     }  
  12.   
  13. }  
  14.   
  15. class Print extends Thread{  
  16.     @Override  
  17.     public void run(){  
  18.         for(int i=0;i<10;i++){  
  19.             System.out.println(Thread.currentThread().getName()+":"+i);  
  20.             try {  
  21.                 Thread.sleep(2000);  
  22.             } catch (InterruptedException e) {  
  23.                 e.printStackTrace();  
  24.             }  
  25.         }  
  26.     }  
  27. }  


执行结果:

 

 

[html]  view plain  copy
 
 
 
  1. Thread-0:0  
  2. Thread-1:0  
  3. Thread-0:1  
  4. Thread-1:1  
  5. Thread-0:2  
  6. Thread-1:2  
  7. Thread-0:3  
  8. Thread-1:3  
  9. Thread-0:4  
  10. Thread-1:4  
  11. Thread-0:5  
  12. Thread-1:5  
  13. Thread-0:6  
  14. Thread-1:6  
  15. Thread-0:7  
  16. Thread-1:7  
  17. Thread-0:8  
  18. Thread-1:8  
  19. Thread-0:9  
  20. Thread-1:9  


2.实现Runnable接口

 

 

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. public class ThreadClient1 {  
  4.   
  5.     public static void main(String[] args) {  
  6.         Runnable p1 = new Salesman("Jack");  
  7.         Runnable p2 = new Salesman("Iris");  
  8.           
  9.         Thread t1 = new Thread(p1);  
  10.         Thread t2 = new Thread(p2);  
  11.           
  12.         t1.start();  
  13.         t2.start();  
  14.     }  
  15.   
  16. }  
  17.   
  18. class Salesman implements Runnable{  
  19.       
  20.     private int ticket=100;//每个线程都拥有100张票  
  21.     private String name;  
  22.     Salesman(String name){  
  23.         this.name=name;  
  24.     }  
  25.       
  26.     @Override  
  27.     public void run(){  
  28.         while(ticket>0){  
  29.              System.out.println(ticket--+" is saled by "+name+","+Thread.currentThread().getName());  
  30.             try {  
  31.                 Thread.sleep(1000);  
  32.             } catch (InterruptedException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.          }  
  36.     }  
  37. }  


执行结果:

 

 

[html]  view plain  copy
 
 
 
  1. 10 is saled by Jack,Thread-0  
  2. 10 is saled by Iris,Thread-1  
  3. 9 is saled by Jack,Thread-0  
  4. 9 is saled by Iris,Thread-1  
  5. 8 is saled by Jack,Thread-0  
  6. 8 is saled by Iris,Thread-1  
  7. 7 is saled by Iris,Thread-1  
  8. 7 is saled by Jack,Thread-0  
  9. 6 is saled by Iris,Thread-1  
  10. 6 is saled by Jack,Thread-0  
  11. 5 is saled by Iris,Thread-1  
  12. 5 is saled by Jack,Thread-0  
  13. 4 is saled by Iris,Thread-1  
  14. 4 is saled by Jack,Thread-0  
  15. 3 is saled by Iris,Thread-1  
  16. 3 is saled by Jack,Thread-0  
  17. 2 is saled by Iris,Thread-1  
  18. 2 is saled by Jack,Thread-0  
  19. 1 is saled by Iris,Thread-1  
  20. 1 is saled by Jack,Thread-0  



 

 

3.实现Callable接口

 

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.ExecutionException;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10.   
  11. public class CallType {  
  12.       
  13.     public static void main(String[] args) {  
  14.         ExecutorService es = Executors.newCachedThreadPool();  
  15.         List<Future<String>> results = new ArrayList<Future<String>>();  
  16.         for(int i=0;i<5;i++){  
  17.             results.add(es.submit(new TaskWithResult(i)));  
  18.         }  
  19.           
  20.         for(Future<String> fs : results){  
  21.             try {  
  22.                 System.out.println(fs.get());  
  23.             } catch (InterruptedException | ExecutionException e) {  
  24.                 // TODO Auto-generated catch block  
  25.                 e.printStackTrace();  
  26.             }  
  27.         }  
  28.     }  
  29. }  
  30.   
  31. class TaskWithResult implements Callable<String>{  
  32.     private int id;  
  33.     public TaskWithResult(int id){  
  34.         this.id = id;  
  35.     }  
  36.     @Override  
  37.     public String call() throws Exception {  
  38.         return "result of TaskWithResult" + id;  
  39.     }  
  40. }  

 

 

执行结果:

 

[html]  view plain  copy
 
 
 
  1. result of TaskWithResult0  
  2. result of TaskWithResult1  
  3. result of TaskWithResult2  
  4. result of TaskWithResult3  
  5. result of TaskWithResult4  

猜你喜欢

转载自www.cnblogs.com/panchanggui/p/9664370.html
今日推荐