Skip to content

Commit 55e2644

Browse files
committed
added Thread sleep
1 parent 05af89a commit 55e2644

File tree

3 files changed

+75
-2
lines changed

3 files changed

+75
-2
lines changed

.idea/workspace.xml

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ It is used to develop rich internet applications. It uses a light-weight user in
129129
|[MultiThreading](https://github.com/connectaman/Java_Notes_and_Programs/blob/master/src/Multithreading/multithreading.md)|
130130
|[Life Cycle of Thread](https://github.com/connectaman/Java_Notes_and_Programs/blob/master/src/Multithreading/LifeCycle.md)|
131131
|[Create Thread](https://github.com/connectaman/Java_Notes_and_Programs/blob/master/src/Multithreading/CreateThread.md)|
132-
|[]()|
132+
|[Thread Sleep]()|
133133
|[]()|
134134
|[]()|
135135

src/Multithreading/ThreadSleep.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
### Sleep method in java
2+
3+
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
4+
5+
##### Syntax of sleep() method in java
6+
7+
The Thread class provides two methods for sleeping a thread:
8+
9+
- public static void sleep(long miliseconds)throws InterruptedException
10+
- public static void sleep(long miliseconds, int nanos)throws InterruptedException
11+
12+
--------
13+
14+
##### Example of sleep method in java
15+
16+
```java
17+
class TestSleepMethod1 extends Thread{
18+
public void run(){
19+
for(int i=1;i<5;i++){
20+
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
21+
System.out.println(i);
22+
}
23+
}
24+
public static void main(String args[]){
25+
TestSleepMethod1 t1=new TestSleepMethod1();
26+
TestSleepMethod1 t2=new TestSleepMethod1();
27+
28+
t1.start();
29+
t2.start();
30+
}
31+
}
32+
```
33+
Output
34+
```
35+
1
36+
1
37+
2
38+
2
39+
3
40+
3
41+
4
42+
4
43+
44+
```
45+
46+
47+
48+
##### Can we start a thread twice
49+
50+
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
51+
52+
Let's understand it by the example given below:
53+
54+
```java
55+
56+
57+
public class TestThreadTwice1 extends Thread{
58+
public void run(){
59+
System.out.println("running...");
60+
}
61+
public static void main(String args[]){
62+
TestThreadTwice1 t1=new TestThreadTwice1();
63+
t1.start();
64+
t1.start();
65+
}
66+
}
67+
```
68+
Output
69+
```
70+
running
71+
Exception in thread "main" java.lang.IllegalThreadStateException
72+
```

0 commit comments

Comments
 (0)