To execute Thread processing, create an instance of Thread class and call its start method. Next, I would like to write the processing content, but if you write a class that implements an interface called Runnable and pass it to "new Thread ();" OK
java
class MyRunnable implements Runnable {
	public void run(){
		for (int i=0; i < 500; i++){
			System.out.print('*');
		}
	}
}
public class Test {
	public static void main(String[] args) {
		MyRunnable r = new MyRunnable();
		Thread t = new Thread(r);
		t.start();
		for (int i=0; i < 500; i++){
			System.out.print('.');
		}
	}
}
It's full of local variables, so I'll omit it.
java
class MyRunnable implements Runnable {
	public void run(){
		for (int i=0; i < 500; i++){
			System.out.print('*');
		}
	}
}
public class Test {
	public static void main(String[] args) {
		new Thread(new MyRunnable()).start();
		for (int i=0; i < 500; i++){
			System.out.print('.');
		}
	}
}
Use an anonymous class to combine the two into one.
java
public class Test {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			public void run(){
				for (int i=0; i < 500; i++){
					System.out.print('*');
				}
			}
		}).start();
		for (int i=0; i < 500; i++){
			System.out.print('.');
		}
	}
}
An interface that has only one abstract method is called a "functional interface" in the sense that only one output is defined for each input. Starting with version 8 of Java, functional interfaces can be replaced with a special notation called lambda expressions.
Replace with lambda expression
java
public class Test {
	public static void main(String[] args) {
		new Thread(() -> {
			for (int i=0; i < 500; i++){
				System.out.print('*');
			}
		}).start();
		for (int i=0; i < 500; i++){
			System.out.print('.');
		}
	}
}
        Recommended Posts