2016-09-15 89 views
0

我需要一個Java 8的多線程示例。java的多線程示例8

我需要能夠手動選擇線程數。

在下面的例子中,我有一個Thread.currentThread()。getName()的問題,我需要使用lambda表達式。

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class Thread { 

    public static void main(String args[]) { 
     ExecutorService service = Executors.newFixedThreadPool(10); 
     for (int i =0; i<100; i++){ 
      service.submit(new Task(i)); 
     } 
    } 

final class Task implements Runnable{ 
    private int taskId; 

    public Task(int id){ 
     this.taskId = id; 
    } 

    @Override 
    public void run() { 
     System.out.println("Task ID : " + this.taskId +" performed by " 
      + Thread.currentThread().getName()); 
    } 
} 
+2

你的主要問題是你命名你的Thread類。所以Thread.currentThread()。getName試圖找到你的類的方法,而不是java.lang.Thread。是的,互聯網充滿了多線程的例子,無法正常工作。對於lambda部分,請參閱[如何從Java8 lambda創建Runnable](http://stackoverflow.com/q/34026903/217324) –

+0

您有什麼問題與Thread.currentThread()。getName()'? – Jhonny007

+0

只需使用'java.lang.Thread.currentThread()。getName()' – Xyaren

回答

3

Lambda可以用IntStream輕鬆完成。

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.stream.IntStream; 

public class ThreadLauncher 
{ 

    public static void main(String args[]) 
    { 
    ExecutorService service = Executors.newFixedThreadPool(10); 
    IntStream.range(0, 100).forEach(i -> service.submit(new Task(i))); 
    } 
} 

final class Task 
    implements Runnable 
{ 
    private int taskId; 

    public Task(int id) 
    { 
    this.taskId = id; 
    } 

    @Override 
    public void run() 
    { 
    System.out.println("Task ID : " + this.taskId + " performed by " 
     + Thread.currentThread().getName()); 
    } 
} 
2

對於拉姆達我建議:

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class Main { 

    public static void main(String args[]) { 
     ExecutorService service = Executors.newFixedThreadPool(10); 
     for (int i =0; i < 100; i++) { 
      final int fi = i; 
      service.submit(() -> System.out.println("Task ID : " + fi +" performed by " 
                + Thread.currentThread().getName())); 
     } 
    } 
} 

,或者如果你想全力以赴的lambda表達式

public class Main { 

    public static void main(String args[]) { 
     ExecutorService service = Executors.newFixedThreadPool(10); 
     IntStream.range(0, 100).forEach(i -> service.submit(() -> System.out.println("Task ID : " + i + " performed by " 
                       + Thread.currentThread().getName()))); 
    } 
}