Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class A{
- // im here to just chill
- int counter=0;
- // synchronized : to make a method accessible to single thread at a time
- public synchronized void increaseCounter(){
- counter++;
- }
- }
- class ThreadViaClass extends Thread{
- String output;
- ThreadViaClass(String output){
- this.output = output;
- }
- // necessary function
- public void run(){
- for(int i=0;i<10;i++){
- System.out.println(this.output);
- // as sleep can throw exception
- try{
- Thread.sleep(500);
- }
- catch(Exception e){
- System.out.println(e);
- }
- }
- }
- }
- // as there is no multiple inheritance in java :(
- class ThreadViaInterface extends A implements Runnable{
- String output;
- ThreadViaInterface(String output){
- this.output = output;
- }
- public void run(){
- for(int i=0;i<10;i++){
- System.out.println(this.output);
- try{
- Thread.sleep(500);
- }
- catch(Exception e){
- System.out.println(e);
- }
- }
- }
- }
- public class Main{
- // as Thread.join() throws an exception
- public static void main(String args[]) throws Exception{
- Thread t1 = new ThreadViaClass("t1");
- Thread t2 = new ThreadViaClass("t2");
- Thread t3 = new Thread(new ThreadViaInterface("t3"));
- // anonymous class with thread name Thread t4
- Thread t4 = new Thread(() ->
- {
- for(int i=0;i<10;i++){
- System.out.println("t4");
- try{
- Thread.sleep(100);
- }catch(Exception e){
- System.out.println(e);
- }
- }
- }, "Thread t4"
- );
- // setting and getting name for easier access
- t1.setName("thread t1");
- System.out.println(t1.getName());
- // priorities by default 5, 1- lowest 10-highest
- t1.setPriority(10);
- System.out.println(t1.getPriority());
- System.out.println(t2.getPriority());
- // Thread.currentThread(); prints main
- System.out.println(Thread.currentThread().getName());
- // start automatically calls Thread.run();
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- // t1 t2 t3 printed in any order as they are running parallely
- // isAlive()
- System.out.println(t1.isAlive());
- // joining t1 t2 t3 with parent thread (here main)
- t1.join();
- t2.join();
- t3.join();
- t4.join();
- // this prints false
- System.out.println(t1.isAlive());
- // printed at last
- System.out.println("Joined with main thread");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement