java实现线程间通信的四种方式
synchronized同步
public class MyObject {
synchronized public void methodA() {
//do something....
}
synchronized public void methodB() {
//do some other thing
}
}
public class ThreadA extends Thread {
private MyObject object;
//省略構(gòu)造方法
@Override
public void run() {
super.run();
object.methodA();
}
}
public class ThreadB extends Thread {
private MyObject object;
//省略構(gòu)造方法
@Override
public void run() {
super.run();
object.methodB();
}
}
public class Run {
public static void main(String[] args) {
MyObject object = new MyObject();
//線程A與線程B 持有的是同一個(gè)對(duì)象:object
ThreadA a = new ThreadA(object);
ThreadB b = new ThreadB(object);
a.start();
b.start();
}
}
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
38
39
40
41
42
43
44
由于線程A和線程B持有同一個(gè)MyObject類的對(duì)象object,盡管這兩個(gè)線程需要調(diào)用不同的方法,但是它們是同步執(zhí)行的,比如:線程B需要等待線程A執(zhí)行完了methodA()方法之后,它才能執(zhí)行methodB()方法。這樣,線程A和線程B就實(shí)現(xiàn)了通信。
這種方式,本質(zhì)上就是“共享內(nèi)存”式的通信。多個(gè)線程需要訪問(wèn)同一個(gè)共享變量,誰(shuí)拿到了鎖(獲得了訪問(wèn)權(quán)限),誰(shuí)就可以執(zhí)行。
while輪詢
其實(shí)就是多線程同時(shí)執(zhí)行,會(huì)犧牲部分CPU性能。
在這種方式下,線程A不斷地改變條件,線程ThreadB不停地通過(guò)while語(yǔ)句檢測(cè)這個(gè)條件(list.size()==5)是否成立 ,從而實(shí)現(xiàn)了線程間的通信。但是這種方式會(huì)浪費(fèi)CPU資源。之所以說(shuō)它浪費(fèi)資源,是因?yàn)镴VM調(diào)度器將CPU交給線程B執(zhí)行時(shí),它沒(méi)做啥“有用”的工作,只是在不斷地測(cè)試 某個(gè)條件是否成立。就類似于現(xiàn)實(shí)生活中,某個(gè)人一直看著手機(jī)屏幕是否有電話來(lái)了,而不是: 在干別的事情,當(dāng)有電話來(lái)時(shí),響鈴?fù)ㄖ猅A電話來(lái)了。
import java.util.ArrayList;
import java.util.List;
public class MyList {
private List<String> list = new ArrayList<String>();
public void add() {
list.add("elements");
}
public int size() {
return list.size();
}
}
import mylist.MyList;
public class ThreadA extends Thread {
private MyList list;
public ThreadA(MyList list) {
super();
this.list = list;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
list.add();
System.out.println("添加了" + (i + 1) + "個(gè)元素");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import mylist.MyList;
public class ThreadB extends Thread {
private MyList list;
public ThreadB(MyList list) {
super();
this.list = list;
}
@Override
public void run() {
try {
while (true) {
if (list.size() == 5) {
System.out.println("==5, 線程b準(zhǔn)備退出了");
throw new InterruptedException();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import mylist.MyList;
import extthread.ThreadA;
import extthread.ThreadB;
public class Test {
public static void main(String[] args) {
MyList service = new MyList();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
}
}
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
wait/notify機(jī)制
public class MyList {
private static List<String> list = new ArrayList<String>();
public static void add() {
list.add("anyString");
}
public static int size() {
return list.size();
}
}
public class ThreadA extends Thread {
private Object lock;
public ThreadA(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
if (MyList.size() != 5) {
System.out.println("wait begin " + System.currentTimeMillis());
lock.wait();
System.out.println("Interruption!!!");
//lock.wait();
lock.notify();
lock.wait();
System.out.println("wait end " + System.currentTimeMillis());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadB extends Thread {
private Object lock;
public ThreadB(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
MyList.add();
if (MyList.size() == 5) {
lock.notify();
System.out.println("已經(jīng)發(fā)出了通知");
lock.wait();
}
System.out.println("添加了" + (i + 1) + "個(gè)元素!");
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
try {
Object lock = new Object();
ThreadA a = new ThreadA(lock);
a.start();
Thread.sleep(50);
ThreadB b = new ThreadB(lock);
b.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
wait begin 1498007974397
添加了1個(gè)元素!
添加了2個(gè)元素!
添加了3個(gè)元素!
添加了4個(gè)元素!
已經(jīng)發(fā)出了通知
Interruption!!!
添加了5個(gè)元素!
添加了6個(gè)元素!
添加了7個(gè)元素!
添加了8個(gè)元素!
添加了9個(gè)元素!
添加了10個(gè)元素!
1
2
3
4
5
6
7
8
9
10
11
12
13
線程A要等待某個(gè)條件滿足時(shí)(list.size()==5),才執(zhí)行操作。線程B則向list中添加元素,改變list 的size。
A,B之間如何通信的呢?也就是說(shuō),線程A如何知道 list.size() 已經(jīng)為5了呢?
這里用到了Object類的 wait() 和 notify() 方法。
當(dāng)條件未滿足時(shí)(list.size() !=5),線程A調(diào)用wait() 放棄CPU,并進(jìn)入阻塞狀態(tài)。—不像②while輪詢那樣占用CPU
當(dāng)條件滿足時(shí),線程B調(diào)用 notify()通知 線程A,所謂通知線程A,就是喚醒線程A,并讓它進(jìn)入可運(yùn)行狀態(tài)。
這種方式的一個(gè)好處就是CPU的利用率提高了。
?
管道通信
管道流主要用來(lái)實(shí)現(xiàn)兩個(gè)線程之間的二進(jìn)制數(shù)據(jù)的傳播,下面以PipedInputStream類和PipedOutputStream類為例,實(shí)現(xiàn)生產(chǎn)者-消費(fèi)者:
package test.pipe;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 我們以數(shù)字替代產(chǎn)品 生產(chǎn)者每5秒提供5個(gè)產(chǎn)品,放入管道
*/
class MyProducer extends Thread {
private PipedOutputStream outputStream;
private int index = 0;
public MyProducer(PipedOutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public void run() {
while (true) {
try {
for (int i = 0; i < 5; i++) {
outputStream.write(index++);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消費(fèi)者每0.5秒從管道中取1件產(chǎn)品,并打印剩余產(chǎn)品數(shù)量,并打印產(chǎn)品信息(以數(shù)字替代)
*/
class MyConsumer extends Thread {
private PipedInputStream inputStream;
public MyConsumer(PipedInputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
int count = inputStream.available();
if (count > 0) {
System.out.println("rest product count: " + count);
System.out.println("get product: " + inputStream.read());
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public class PipeTest1 {
public static void main(String[] args) {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try {
pis.connect(pos);
} catch (IOException e) {
e.printStackTrace();
}
new MyProducer(pos).start();
new MyConsumer(pis).start();
}
}
---------------------
作者:Hadwin1991
來(lái)源:CSDN
原文:https://blog.csdn.net/Hadwin1991/article/details/73527835
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請(qǐng)附上博文鏈接!
轉(zhuǎn)載于:https://www.cnblogs.com/lgyxrk/p/10404846.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的java实现线程间通信的四种方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Docker学习笔记之保存和共享镜像
- 下一篇: MFC文件打开和保存