📜  如何在Java中使用 Lambda 表达式创建线程?

📅  最后修改于: 2022-05-13 01:54:34.834000             🧑  作者: Mango

如何在Java中使用 Lambda 表达式创建线程?

Lambda 表达式是在Java SE8 中引入的。这些表达式是为功能接口开发的。函数式接口是只有一个抽象方法的接口。要了解有关 Lambda 表达式的更多信息,请单击此处。

句法:

这里我们使用Runnable Interface 。由于它是一个函数式接口,因此可以使用 Lambda 表达式。执行以下步骤来完成任务:

  • 创建 Runnable 接口引用并为 run() 方法编写 Lambda 表达式。
  • 创建一个 Thread 类对象,传递上面创建的 Runnable 接口的引用,因为 start() 方法是在 Thread 类中定义的,它的对象需要创建。
  • 调用 start() 方法来运行线程。

例子

示例 1:

Java
public class Test {
 
    public static void main(String[] args)
    {
 
        // Creating Lambda expression for run() method in
        // functional interface "Runnable"
        Runnable myThread = () ->
        {
 
            // Used to set custom name to the current thread
            Thread.currentThread().setName("myThread");
            System.out.println(
                Thread.currentThread().getName()
                + " is running");
        };
 
        // Instantiating Thread class by passing Runnable
        // reference to Thread constructor
        Thread run = new Thread(myThread);
 
        // Starting the thread
        run.start();
    }
}


Java
public class Test {
 
    public static void main(String[] args)
    {
        Runnable basic = () ->
        {
 
            String threadName
                = Thread.currentThread().getName();
            System.out.println("Running common task by "
                               + threadName);
        };
 
        // Instantiating two thread classes
        Thread thread1 = new Thread(basic);
        Thread thread2 = new Thread(basic);
 
        // Running two threads for the same task
        thread1.start();
        thread2.start();
    }
}


Java
import java.util.Random;
 
// This is a random player class with two functionalities
// playGames and playMusic
class RandomPlayer {
 
    public void playGame(String gameName)
        throws InterruptedException
    {
 
        System.out.println(gameName + " game started");
 
        // Assuming game is being played for 500
        // milliseconds
        Thread.sleep(500); // this statement may throw
                           // interrupted exception, so
                           // throws declaration is added
 
        System.out.println(gameName + " game ended");
    }
 
    public void playMusic(String trackName)
        throws InterruptedException
    {
 
        System.out.println(trackName + " track started");
 
        // Assuming music is being played for 500
        // milliseconds
        Thread.sleep(500); // this statement may throw
                           // interrupted exception, so
                           // throws declaration is added
 
        System.out.println(trackName + " track ended");
    }
}
 
public class Test {
 
    // games and tracks arrays which are being used for
    // picking random items
    static String[] games
        = { "COD",      "Prince Of Persia", "GTA-V5",
            "Valorant", "FIFA 22",          "Fortnite" };
    static String[] tracks
        = { "Believer", "Cradles", "Taki Taki", "Sorry",
            "Let Me Love You" };
 
    public static void main(String[] args)
    {
 
        RandomPlayer player
            = new RandomPlayer(); // Instance of
                                  // RandomPlayer to access
                                  // its functionalities
 
        // Random class for choosing random items from above
        // arrays
        Random random = new Random();
 
        // Creating two lambda expressions for runnable
        // interfaces
        Runnable gameRunner = () ->
        {
 
            try {
 
                player.playGame(games[random.nextInt(
                    games.length)]); // Choosing game track
                                     // for playing
            }
            catch (InterruptedException e) {
 
                e.getMessage();
            }
        };
 
        Runnable musicPlayer = () ->
        {
 
            try {
 
                player.playMusic(tracks[random.nextInt(
                    tracks.length)]); // Choosing random
                                      // music track for
                                      // playing
            }
            catch (InterruptedException e) {
 
                e.getMessage();
            }
        };
 
        // Instantiating two thread classes with runnable
        // references
        Thread game = new Thread(gameRunner);
        Thread music = new Thread(musicPlayer);
 
        // Starting two different threads
        game.start();
        music.start();
 
        /*
         *Note: As we are dealing with threads output may
         *differ every single time we run the program
         */
    }
}


输出
myThread is running

示例 2:

使用 lambda 表达式的多线程-1

Java

public class Test {
 
    public static void main(String[] args)
    {
        Runnable basic = () ->
        {
 
            String threadName
                = Thread.currentThread().getName();
            System.out.println("Running common task by "
                               + threadName);
        };
 
        // Instantiating two thread classes
        Thread thread1 = new Thread(basic);
        Thread thread2 = new Thread(basic);
 
        // Running two threads for the same task
        thread1.start();
        thread2.start();
    }
}
输出
Running common task by Thread-1
Running common task by Thread-0

示例 3:

使用 lambda 表达式的多线程 2

Java

import java.util.Random;
 
// This is a random player class with two functionalities
// playGames and playMusic
class RandomPlayer {
 
    public void playGame(String gameName)
        throws InterruptedException
    {
 
        System.out.println(gameName + " game started");
 
        // Assuming game is being played for 500
        // milliseconds
        Thread.sleep(500); // this statement may throw
                           // interrupted exception, so
                           // throws declaration is added
 
        System.out.println(gameName + " game ended");
    }
 
    public void playMusic(String trackName)
        throws InterruptedException
    {
 
        System.out.println(trackName + " track started");
 
        // Assuming music is being played for 500
        // milliseconds
        Thread.sleep(500); // this statement may throw
                           // interrupted exception, so
                           // throws declaration is added
 
        System.out.println(trackName + " track ended");
    }
}
 
public class Test {
 
    // games and tracks arrays which are being used for
    // picking random items
    static String[] games
        = { "COD",      "Prince Of Persia", "GTA-V5",
            "Valorant", "FIFA 22",          "Fortnite" };
    static String[] tracks
        = { "Believer", "Cradles", "Taki Taki", "Sorry",
            "Let Me Love You" };
 
    public static void main(String[] args)
    {
 
        RandomPlayer player
            = new RandomPlayer(); // Instance of
                                  // RandomPlayer to access
                                  // its functionalities
 
        // Random class for choosing random items from above
        // arrays
        Random random = new Random();
 
        // Creating two lambda expressions for runnable
        // interfaces
        Runnable gameRunner = () ->
        {
 
            try {
 
                player.playGame(games[random.nextInt(
                    games.length)]); // Choosing game track
                                     // for playing
            }
            catch (InterruptedException e) {
 
                e.getMessage();
            }
        };
 
        Runnable musicPlayer = () ->
        {
 
            try {
 
                player.playMusic(tracks[random.nextInt(
                    tracks.length)]); // Choosing random
                                      // music track for
                                      // playing
            }
            catch (InterruptedException e) {
 
                e.getMessage();
            }
        };
 
        // Instantiating two thread classes with runnable
        // references
        Thread game = new Thread(gameRunner);
        Thread music = new Thread(musicPlayer);
 
        // Starting two different threads
        game.start();
        music.start();
 
        /*
         *Note: As we are dealing with threads output may
         *differ every single time we run the program
         */
    }
}
输出
Believer track started
GTA-V5 game started
Believer track ended
GTA-V5 game ended