Java多线程的几种写法

  

Java多线程的在开发中用到的很多,简单总结一下几种写法,分别是继承线方法,实现运行的接口,实现可调用的接口。
1。继承线方法

  
 <代码>类TestThread扩展线程{
  字符串名称;
  公共TestThread(字符串名称){
  this.name=名称;
  }
  @Override
  公共空间run () {
  for (int i=0;我& lt;6;我+ +){
  System.out.println (this.name +“:”+ i);
  }
  }
  } 
  

主方法调用:
线程启动有两个方法,一个是开始()方法,一个是运行()方法,但是直接调用运行方法时线程不会交替运行,而是顺序执行,只有开始用方法时才会交替执行

  
 <代码> TestThread tt1=new TestThread (“A”);
  TestThread tt2=new TestThread (" B ");
  tt1.start ();
  tt2.start();  
  

运行结果:
癑ava多线程的几种写法”
2。实现运行的接口,有多种写法
2.1外部类

  
 <代码>类TestRunnable实现Runnable {
  字符串名称;
  公共TestRunnable(字符串名称){
  this.name=名称;
  }
  @Override
  公共空间run () {
  for (int i=0;我& lt;6;我+ +){
  System.out.println (this.name +“:”+ i);
  }
  }
  } 
  

调用:   

 <代码> TestRunnable tr1=new TestRunnable (“C”);
  TestRunnable tr2=new TestRunnable (“D”);
  新线程(tr1) .start ();
  新线程(tr2) .start();  
  

2.2匿名内部类方式

  
 <代码>新线程(新Runnable () {
  
  @Override
  公共空间run () {//TODO自动生成方法存根
  
  }
  }).start();  
  

2.3λ表达式,jdk1.8,只要是函数式接口,都可以使用λ表达式或者方法引用

  
 <代码>新线程(()→{
  for (int i=0;我& lt;6;我+ +){
  System.out.println(我);
  }
  }).start();  
  

2.4 executorservice创建线程池的方式

  
 <代码>类TestExecutorService实现Runnable {
  字符串名称;
  公共TestExecutorService(字符串名称){
  this.name=名称;
  }
  @Override
  公共空间run () {
  for (int i=0;我& lt;6;我+ +){
  System.out.println (this.name +“:”+ i);
  }
  }
  } 
  

调用:可以创建固定个数的线程池

  
 <代码>=Executors.newFixedThreadPool ExecutorService池(2);
  TestExecutorService tes1=new TestExecutorService (“E”);
  TestExecutorService tes2=new TestExecutorService (“F”);
  pool.execute (tes1);
  pool.execute (tes2);
  pool.shutdown();  
  
 <代码>运行结果跟2.1差不多 
  

癑ava多线程的几种写法"

  

3。实现可调用的接口,可以返回结果

  
 <代码>//Callable提供返回数据,根据需要返回不同类型
  类TestCallable实现Callable 0)
  System.out.println(“买的票,票=" + this.ticket——);
  }
  返回“票卖完了”;
  }
  } 
  

调用:   

 <代码> Callabletc=new TestCallable ();
  FutureTask任务=new FutureTask (tc);
  新线程(任务).start ();
  尝试{
  System.out.println (task.get());//获取返回值
  }捕捉(InterruptedException | ExecutionException e) {//TODO自动生成的catch块
  e.printStackTrace ();
  } 
  
 <代码>运行结果: 
  

癑ava多线程的几种写法"

Java多线程的几种写法