- Java
- Basics
- Classes
- Objects
- Arrays
- Variables
- Loops
- Numbers
- Strings
- Exceptions
- Regexp
- OOP
- Inheritance
- Polymorphism
- Static Keyword
- Abstract Keyword
- Interfaces
- Constructors
- Packages
- Nested Classes
- Final Keyword
- Swing
- Frame
- Panel
- Listener
- Combo Box
- Label
- Image
- Menu
- Table
- Layout
- Drawing
- Timer
- Designer
- Collections
- Lists
- Comparable
- Sets
- Maps
- Generics
- Properties
- Streams
- Json
- Compiler
- Sublime Text
- Apache Ant
- IO
- Streams Io
- Socket
- Watching Files
- Logger
- Clipboard
- Encrypt
- Junit
- About
- Test Case
- Suite Test
- Annotations
- Exceptions
- JavaFX
- Openjfx
- Scene Builder
- First App
- Jar Archive
- On Action
- Change Listener
- Maven
- Demo
- Spring Boot
- Junit
- Guava
- Threads
- Create Thread ♣
- Sleep
- Lock
- Scheduler
Extending
Create a thread by extending Thread class.
/**
* Threads are not separate processes on the OS user feels is like ...
* separate processes.
*
* A Java application starts up a main thread, main() on the bottom ...
* of the stack.
*
* A new thread creats a separate call stack, run() at the botttom ...
* of the stack.
*
* Threads can be created by using two mechanisms, extending Thread class ...
* or implementing Runnable.
*/
package com.minte9.threads.create_thread;
public class Extending extends Thread { // Look Here
public static void main(String[] args) {
Thread t1 = new Extending();
Thread t2 = new Extending();
Thread t3 = new Extending();
t1.start();
t2.start();
t3.start();
/*
Thread-2
Thread-1
Thread-0
Thread-2
Thread-0
Thread-1
*/
}
public void run() {
try {
String name = Thread.currentThread().getName();
System.out.println(name);
Thread.sleep(1000);
System.out.println(name);
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
}
Implementing
Best practice is to implement Runnable.
/**
* Thread implementing Runnable.
* Using lambdas the code is more concise and easy to read.
*/
package com.minte9.threads.create_thread;
public class Implementing {
public static void main(String[] args)
throws InterruptedException {
System.out.println(Thread.currentThread().getName()); // main
new Thread(new MyClass()).start(); // Tread-0
new Thread(new Runnable() {
public void run() {
System.out.println(
Thread.currentThread().getName()
);
}
}).start(); // Thread-1
new Thread(() -> { // Lambdas
System.out.println(
Thread.currentThread().getName()
);
}).start(); // Thread-2
System.out.println("Back in Main");
/*
main
Thread-0
Thread-1
Back in Main
Thread-2
*/
}
}
class MyClass implements Runnable {
@Override public void run() {
System.out.println(
Thread.currentThread().getName()
);
}
}