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多线程运行程序