线程的建立体式格局
1、继续Thread类完成多线程
2、覆写Runnable()接口完成多线程,然后一样覆写run()。引荐此体式格局
3、运用Callable和Future建立线程
相干视频教程引荐:java进修视频
实例以下:
1、继续Thread类完成多线程
/* * 继续Thread类建立线程 * 1、重写run要领 * 2、建立thread类的实例,即建立线程对象 * 3、挪用线程对象的start()来启动该线程 * 注重:Thread类的每一个历程之间不能同享该实例变量;具有单继续范围 * */ public class StartThread extends Thread{ private int i; @Override //重写run要领 public void run() { // TODO Auto-generated method stub for(i=0;i<10;i++) { System.out.println(getName()+" "+i); } } public static void main(String[] args) { for(int i=0;i<10;i++) { System.out.println(Thread.currentThread().getName()+ " ,"+i); //建立thread类的实例 StartThread h1=new StartThread(); StartThread h2=new StartThread(); if(i==2) { //启动第一个历程 h1.start(); //启动第二个历程 h2.start(); } } } }
2、覆写Runnable()接口完成多线程,然后一样覆写run()
定义Runnable()接口的完成类,重写Run()要领。
建立Runnable完成类的实例,并以此实例作为Thread的target来建立Thread对象。这个Thread对象才是真正的线程对象
经由过程挪用线程对象的start()要领来启动线程
/*建立线程体式格局二 * 1、建立:完成Runnable+重写run * 2、启动:建立完成类对象+Thread对象+start * * 注重:引荐运用,防止单继续的范围性,优先运用接口 * 轻易同享资源 * */ public class MyThread2 implements Runnable {//完成Runnable接口 public void run(){ //重写run要领 // TODO Auto-generated method stub //当线程类完成Runnable接口时 //假如想要猎取当前线程,只能运用Thread.currentThread要领 for(;i<100;i++) { System.out.println(Thread.currentThread().getName()+" "+i); } } public class Main { public static void main(String[] args){ //启动线程1 //不像继续Thread类一样,直接能够实例化对象即可,Runnable接口必需要 //先建立实例,再将此实例作为Thread的target来建立Thread对象 //建立并启动线程 MyThread2 myThread=new MyThread2(); Thread thread=new Thread(myThread); thread().start(); //或许 new Thread(new MyThread2()).start(); } }
3、运用Callable和Future建立线程
和Runnable接口不一样,Callable接口供应了一个call()要领作为线程实行体,call()要领比run()要领功用要壮大。
call()要领能够有返回值
call()要领能够声明抛出非常
public class Main { public static void main(String[] args){ MyThread3 th=new MyThread3(); //运用Lambda表达式建立Callable对象 //运用FutureTask类来包装Callable对象 FutureTask<Integer> future=new FutureTask<Integer>( (Callable<Integer>)()->{ return 5; } ); //实质上还是以Callable对象来建立并启动线程 new Thread(task,"有返回值的线程").start(); try{ //get()要领会壅塞,直到子线程实行完毕才返回 System.out.println("子线程的返回值:"+future.get()); }catch(Exception e){ ex.printStackTrace(); } } }
相干文章教程引荐:java编程入门
以上就是java中建立线程有几种体式格局的细致内容,更多请关注ki4网别的相干文章!