Last active
May 22, 2017 13:26
-
-
Save nkonev/da8ab13bc6c5a5ee65da7a69383c02be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package p; | |
| import org.slf4j.Logger; | |
| import org.slf4j.LoggerFactory; | |
| /** | |
| * Created by nkonev on 22.05.17. | |
| */ | |
| public class ImmutableStatelessInterfaceInstanceForThread { | |
| public static void main(String[] args) throws InterruptedException { | |
| // this is lambda which implicitly creates MyRunnable instance with getContext() method which returns new MyRunnable.MyContext | |
| // casting to MyRunnable is required | |
| Thread thread = new Thread((MyRunnable) () -> new MyRunnable.MyContext(666, "Никита")); | |
| thread.start(); | |
| thread.join(); | |
| } | |
| private interface MyRunnable extends Runnable { | |
| // interface allows only static final which forces you make immutably Runnables | |
| Logger LOGGER = LoggerFactory.getLogger(MyRunnable.class); | |
| MyContext getContext(); | |
| @Override | |
| default void run() { | |
| final MyContext c = getContext(); | |
| LOGGER.info("hello, #{} {}", c.getId(), c.getName()); | |
| } | |
| class MyContext { | |
| private final int id; | |
| private final String name; | |
| public MyContext(int id, String name) { | |
| this.id = id; | |
| this.name = name; | |
| } | |
| public int getId() { | |
| return id; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment