Skip to content

Instantly share code, notes, and snippets.

@striver-007
Created June 27, 2021 08:57
Show Gist options
  • Save striver-007/5d1eb984e9b14d35795cdf07e4c1204b to your computer and use it in GitHub Desktop.
Save striver-007/5d1eb984e9b14d35795cdf07e4c1204b to your computer and use it in GitHub Desktop.
Runnable Interface in Java
package com.company;
// There are two ways to create a thread in java :
//
// By Extending Thread Class
// By implementing Runnable interface
// **************Implementing runnable interface***********
//Steps To Create A Java Thread Using Runnable Interface:
// 1-> Create a class and implement the Runnable interface by using the implements keyword.
// 2-> Override the run() method inside the implementer class.
// 3-> Create an object of the implementer class in the main() method.
// 4-> Instantiate the Thread class and pass the object to the Thread constructor.
// 5-> Call start() on the thread. start()will call the run()method.
class runnableThread1 implements Runnable {
public void run() {
int i = 0;
while (i < 10000) {
System.out.println("I m thread 1 in threat 1");
i++;
}
}
}
class runnableThread2 implements Runnable {
public void run() {
int j = 0;
while (j < 10000) {
System.out.println("I m thread 2 in threat 2");
j++;
}
}
}
public class CWH_71_RunnableInterface {
public static void main(String[] args) {
runnableThread1 bullet1 = new runnableThread1();
Thread gun1 = new Thread(bullet1);
gun1.start();
runnableThread2 bullet2 = new runnableThread2();
Thread gun2 = new Thread(bullet2);
gun2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment