1
2package com.journaldev.threads;
3
4public class ThreadSleep {
5
6 public static void main(String[] args) throws InterruptedException {
7 long start = System.currentTimeMillis();
8 Thread.sleep(2000);
9 System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start));
10
11 }
12
13}
14
1class ThreadJoining extends Thread
2{
3 @Override
4 public void run()
5 {
6 for (int i = 0; i < 2; i++)
7 {
8 try
9 {
10 Thread.sleep(500);
11 System.out.println("Current Thread: "
12 + Thread.currentThread().getName());
13 }
14
15 catch(Exception ex)
16 {
17 System.out.println("Exception has" +
18 " been caught" + ex);
19 }
20 System.out.println(i);
21 }
22 }
23}
24
25class GFG
26{
27 public static void main (String[] args)
28 {
29 ThreadJoining t1 = new ThreadJoining();
30 ThreadJoining t2 = new ThreadJoining();
31 ThreadJoining t3 = new ThreadJoining();
32 t1.start();
33 try
34 {
35 System.out.println("Current Thread: "
36 + Thread.currentThread().getName());
37 t1.join();
38 }
39 catch(Exception ex)
40 {
41 System.out.println("Exception has " +
42 "been caught" + ex);
43 }
44 t2.start();
45 try
46 {
47 System.out.println("Current Thread: "
48 + Thread.currentThread().getName());
49 t2.join();
50 }
51 catch(Exception ex)
52 {
53 System.out.println("Exception has been" +
54 " caught" + ex);
55 }
56 t3.start();
57 }
58}
1public class ClassName extends Thread{
2 public void run(){
3 super.run();
4 //Your Code
5 }
6}
7
8public class Main{
9 public static void main(String[] args){
10 ClassName thread = new ClassName();
11 thread.start();
12 }
13}
1// Copy and test
2// They run simultaneously
3
4public static void main(String[] args) {
5 // How to create a thread
6 Thread thread = new Thread(new Runnable() {
7 @Override
8 // Loop running in thread
9 public void run() {
10 for (int i = 0; i < 20; i++) {
11 System.out.println("Printing plus " + i + " in a worker thread.");
12 try {
13 Thread.sleep(1000);
14 } catch(Exception e) {
15 e.printStackTrace();
16 }
17 }
18 }
19 });
20 thread.start();
21 // Loop running in main thread
22 for (int j = 0; j < 20 ; j++) {
23 System.out.println("Printing plus " + j + " in a main thread.");
24 try {
25 Thread.sleep(900);
26 } catch(Exception e) {
27 e.printStackTrace();
28 }
29 }
30 }
1class RunnableObject implements Runnable {
2 private Thread t;
3 private String threadName;
4
5 RunnableObject( String name) {
6 System.out.println("Creating " + threadName );
7 threadName = name;
8 t = new Thread (this, threadName);
9 }
10
11 public void run() {
12 System.out.println("Running " + threadName );
13 }
14
15 public void start () {
16 System.out.println("Starting " + threadName );
17 t.start ();
18 }
19}
20
21public class TestThread {
22
23 public static void main(String args[]) {
24 RunnableObject R1 = new RunnableObject( "Thread-1");
25 R1.start();
26 }
27}
1public static void main(String[] args {
2 ...
3 Thread t1= new Thread(...);
4 t1.start();
5 ...
6}