java线程通信方式:使用wait/notify机制实现线程间的同步通信

Java线程通信方式是指多个线程之间如何进行数据交换的方式。它可以通过共享变量、等待/通知机制、管道流和Socket等方式实现。

Java线程通信方式是指多个线程之间如何进行数据交换的方式。它可以通过共享变量、等待/通知机制、管道流和Socket等方式实现。

1. 共享变量

共享变量是指多个线程可以访问的变量,它可以用来实现线程间的通信。

示例代码:

public class ThreadCommunicationDemo {

public static void main(String[] args) {

Data data = new Data();

new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

data.increment();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

data.decrement();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

}

}

class Data {

private int num = 0;

public synchronized void increment() throws InterruptedException {

// 1. 判断

while (num != 0) {

// 等待

this.wait();

}

// 2. 干活

num++;

System.out.println(Thread.currentThread().getName() + "=>" + num);

// 3. 通知

this.notifyAll();

}

public synchronized void decrement() throws InterruptedException {

// 1. 判断

while (num == 0) {

// 等待

this.wait();

}

// 2. 干活

num--;

System.out.println(Thread.currentThread().getName() + "=>" + num);

// 3. 通知

this.notifyAll();

}

}

2. 等待/通知机制

等待/通知机制是指线程之间通过Object类中的wait()、notify()和notifyAll()方法实现线程间通信的一种机制。

示例代码:

public class ThreadCommunicationDemo {

public static void main(String[] args) {

Data data = new Data();

new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

data.increment();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

data.decrement();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

}

}

class Data {

private int num = 0;

public synchronized void increment() throws Interrupted

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(495)
win7安装程序正在应用系统设置安装程序的应用
上一篇
window显示文件后缀名:Using Windows to Identify File Extensions
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(23条)