
一、 線程停止(建議讓線程自己停下來)
建立一個标志flag,當flag = false,線程停止
1 package TestStop;
2
3 //實作類
4 public class TestStop implements Runnable {
5 //自定義一個flag标志
6 private boolean flag = true;
7
8 @Override
9 public void run() {
10 int i = 0;
11 while (flag) {
12 System.out.println("run..." + (i++));
13 }
14 }
15
16 //停止方法
17 public void stop() {
18 this.flag = false;
19 }
20
21 //主線程
22 public static void main(String[] args) {
23 //建立線程并啟動
24 TestStop testStop = new TestStop();
25 new Thread(testStop).start();
26
27 for (int i = 0; i < 100; i++) {
28 System.out.println("main" + i);
29 //90時停止線程
30 if (i == 90) {
31 testStop.stop();
32 System.out.println("線程已停止");
33 }
34 }
35 }
36 }
二、線程休眠
通過Thread調用sleep()
1 //模拟延時能放大問題
2 public class TestSleep implements Runnable {
3 private int tickets = 10;
4
5 //買火車票
6 @Override
7 public void run() {
8 while (true) {
9 if (tickets <= 0) {
10 break;
11 }
12 //模拟網絡延時,若不模拟(去掉這段代碼),看起來是正常的
13 try {
14 Thread.sleep(100);//100毫秒
15 } catch (InterruptedException e) {
16 e.printStackTrace();
17 }
18 System.out.println(Thread.currentThread().getName() + "拿到了第" + tickets-- + "張票");
19 }
20 }
21
22 public static void main(String[] args) {
23 //這裡的一個對象,多個線程并不安全,隻是示範友善是以這樣寫
24 //一個對象
25 TestSleep testSleep = new TestSleep();
26 //多個線程
27 new Thread(testSleep, "小明").start();
28 new Thread(testSleep, "小強").start();
29 new Thread(testSleep, "小紅").start();
30 }
31 }
三、線程禮讓(Thread.yield())
①讓目前正在執行的線程暫停,但是并不阻塞
②将線程從運作狀态轉換成就緒狀态
③讓CPU重新排程,禮讓不一定成功,看CPU心情
1 public class TestYield {
2 public static void main(String[] args) {
3 MyYield myYield = new MyYield();
4 new Thread(myYield, "a").start();
5 new Thread(myYield, "b").start();
6 }
7 }
8
9 class MyYield implements Runnable{
10 @Override
11 public void run() {
12 System.out.println(Thread.currentThread().getName()+"線程開始執行");
13 Thread.yield();//禮讓
14 System.out.println(Thread.currentThread().getName()+"線程結束執行");
15 }
16 }
1 public class TestJoin implements Runnable {
2
3 @Override
4 public void run() {
5 for (int i = 0; i < 500; i++) {
6 System.out.println("vip來了" + i);
7 }
8 }
9
10 public static void main(String[] args) throws InterruptedException {
11
12 TestJoin testJoin = new TestJoin();
13 Thread thread = new Thread(testJoin);//建立代理對象,因為後面需要通過這個代理對象去調用jion()
14 thread.start();
15 for (int i = 0; i < 1000; i++) {
16
17 System.out.println("普通人排隊" + i);
18 if (i == 10) {//還沒到10的時候是很正常的多線程,之後就先讓vip走完
19 thread.join();
20 }
21 }
22 }
23 }