一、多线程的sleep方法
1.Thread.sleep(毫秒)
2.sleep方法是一个静态方法
3.该方法的作用:阻塞当前线程,腾出CPU,让给其他线程
4.sleep的异常注意事项,以及中断休眠的一种方式及其注意点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.bjpowernode.java_learning;
public class D106_1_ {
public static void main(String[] args) throws InterruptedException{
Processer106 p1 = new Processer106();
p1.start();
Thread.sleep( 500 );
p1.interrupt();
for ( int i= 0 ;i< 5 ;i++) {
System.out.println(Thread.currentThread().getName()+ "---->" +i);
Thread.sleep( 200 );
}
}
}
class Processer106 extends Thread{
public void run() {
for ( int i= 0 ;i< 5 ;i++) {
System.out.println(Thread.currentThread().getName()+ "--->" +i);
try {
Thread.sleep( 1000 );
System.out.println(i);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
二、如何正确的停止一个线程(不使用interrupt方法)
使用一个flag就可以达到我们的目的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
packagepackage com.bjpowernode.java_learning;
public class D106_2_InterruptSleep {
public static void main(String[] args) throws Exception{
Processer106_2 p = new Processer106_2();
Thread t = new Thread(p);
t.setName( "t" );
t.start();
Thread.sleep( 5000 );
p.run1 = false ;
}
}
class Processer106_2 implements Runnable{
Boolean run1 = true ;
public void run() {
for ( int i= 0 ;i< 10 ;i++) {
if (run1) {
try {
Thread.sleep( 1000 );
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ "-->" +i);
} else {
return ;
}
}
}
}
|
三、Thread.yield
1.该方法是一个静态方法
2.作用:给同一个优先级的线程让位,但是让位时间不固定
3.和sleep方法相同,就是yield时间不固定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.bjpowernode.java_learning;
public class D106_3_ThreadYield {
public static void main(String[] args) throws InterruptedException {
Processer106_3 p = new Processer106_3();
Thread t = new Thread(p);
t.setName( "t" );
t.start();
for ( int i= 0 ;i< 1000 ;i++) {
System.out.println(Thread.currentThread().getName()+ "-->" +i);
}
}
}
class Processer106_3 implements Runnable{
public void run() {
for ( int i= 0 ;i< 1000 ;i++) {
System.out.println(Thread.currentThread().getName()+ "-->" +i);
if (i% 20 == 0 ) {
Thread.yield();
}
}
}
}
|
四、源码:
|