java8多线程运行程序_Java代码可在程序中运行多个线程

java8多线程运行程序

The task is to execute / run multiple threads in a program in java.

任务是在Java程序中执行/运行多个线程。

In the below code, we are creating a static method printNumbers() to print numbers from 1 to 10, creating two threads one and two, and initializing them with the method using Main::printNumbers.

在下面的代码中,我们将创建一个静态方法printNumbers()来打印从1到10的数字,创建两个线程1和2 ,并使用Main :: printNumbers方法初始化它们。

Code:

码:

public class Main {
    //method to print numbers from 1 to 10
    public static void printNumbers() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }

    //main code	
    public static void main(String[] args) {
        //thread object creation
        Thread one = new Thread(Main::printNumbers);
        Thread two = new Thread(Main::printNumbers);

        //starting the threads
        one.start();
        two.start();
    }
}

Output

输出量

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Initializing threads with different methods

用不同的方法初始化线程

public class Main {
    //method1 - printing numbers from 1 to 10
    public static void printNumbers1() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }

    //method2 - printing numbers from 10 to 1
    public static void printNumbers2() {
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        //printing new line
        System.out.println();
    }	

    //main code	
    public static void main(String[] args) {
        //thread object creation
        Thread one = new Thread(Main::printNumbers1);
        Thread two = new Thread(Main::printNumbers2);

        //starting the threads
        one.start();
        two.start();
    }
}

Output

输出量

10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10


翻译自: https://www.includehelp.com/java-programs/run-multiple-threads-in-a-program.aspx

java8多线程运行程序

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值