java 线程间通信

不同线程间进行通信通常有两种简单方法:
方法一 通过访问共享变量的方式(注:需要处理同步问题)
方法二 通过管道流

其中方法一有两种实现方法,即
方法一a)通过内部类实现线程的共享变量
代码如下:

Java代码 复制代码
  1. /**  
  2.  * 通过内部类实现线程的共享变量  
  3.  *  
  4.  */  
  5. public class Innersharethread {   
  6.     public static void main(String[] args) {   
  7.         Mythread mythread = new Mythread();   
  8.         mythread.getThread().start();   
  9.         mythread.getThread().start();   
  10.         mythread.getThread().start();   
  11.         mythread.getThread().start();   
  12.     }   
  13. }   
  14. class Mythread {   
  15.     int index = 0;   
  16.   
  17.     private class InnerThread extends Thread {   
  18.         public synchronized void run() {   
  19.             while (true) {   
  20.                 System.out.println(Thread.currentThread().getName()   
  21.                         + "is running and index is " + index++);   
  22.             }   
  23.         }   
  24.     }   
  25.   
  26.     public Thread getThread() {   
  27.         return new InnerThread();   
  28.     }   
  29. }  
/**
 * 通过内部类实现线程的共享变量
 *
 */
public class Innersharethread {
	public static void main(String[] args) {
		Mythread mythread = new Mythread();
		mythread.getThread().start();
		mythread.getThread().start();
		mythread.getThread().start();
		mythread.getThread().start();
	}
}
class Mythread {
	int index = 0;

	private class InnerThread extends Thread {
		public synchronized void run() {
			while (true) {
				System.out.println(Thread.currentThread().getName()
						+ "is running and index is " + index++);
			}
		}
	}

	public Thread getThread() {
		return new InnerThread();
	}
}


方法二b)通过实现Runnable接口实现线程的共享变量
代码如下

Java代码 复制代码
  1. /**   
  2. * 通过实现Runnable接口实现线程的共享变量   
  3. * @author Administrator   
  4.  
  5. */    
  6. public class Interfacaesharethread {    
  7. public static void main(String[] args) {    
  8. Mythread mythread = new Mythread();    
  9. new Thread(mythread).start();    
  10. new Thread(mythread).start();    
  11. new Thread(mythread).start();    
  12. new Thread(mythread).start();    
  13. }    
  14. }    
  15.   
  16. /* 实现Runnable接口 */    
  17. class Mythread implements Runnable {    
  18. int index = 0;    
  19.   
  20. public synchronized void run() {    
  21. while (true)    
  22. System.out.println(Thread.currentThread().getName()    
  23. "is running and the index is " + index++);    
  24. }    
  25. }   
/** 
* 通过实现Runnable接口实现线程的共享变量 
* @author Administrator 
* 
*/ 
public class Interfacaesharethread { 
public static void main(String[] args) { 
Mythread mythread = new Mythread(); 
new Thread(mythread).start(); 
new Thread(mythread).start(); 
new Thread(mythread).start(); 
new Thread(mythread).start(); 
} 
} 

/* 实现Runnable接口 */ 
class Mythread implements Runnable { 
int index = 0; 

public synchronized void run() { 
while (true) 
System.out.println(Thread.currentThread().getName() 
+ "is running and the index is " + index++); 
} 
} 


方法二:
代码如下

Java代码 复制代码
  1. import java.io.IOException;    
  2. import java.io.PipedInputStream;    
  3. import java.io.PipedOutputStream;    
  4.   
  5. public class CommunicateWhitPiping {    
  6. public static void main(String[] args) {    
  7. /**   
  8. * 创建管道输出流   
  9. */    
  10. PipedOutputStream pos = new PipedOutputStream();    
  11. /**   
  12. * 创建管道输入流   
  13. */    
  14. PipedInputStream pis = new PipedInputStream();    
  15. try {    
  16. /**   
  17. * 将管道输入流与输出流连接   
  18. * 此过程也可通过重载的构造函数来实现   
  19. */    
  20. pos.connect(pis);    
  21. catch (IOException e) {    
  22. e.printStackTrace();    
  23. }    
  24. /**   
  25. * 创建生产者线程   
  26. */    
  27. Producer p = new Producer(pos);    
  28. /**   
  29. * 创建消费者线程   
  30. */    
  31. Consumer c = new Consumer(pis);    
  32. /**   
  33. * 启动线程   
  34. */    
  35. p.start();    
  36. c.start();    
  37. }    
  38. }    
  39.   
  40. /**   
  41. * 生产者线程(与一个管道输入流相关联)   
  42.  
  43. */    
  44. class Producer extends Thread {    
  45. private PipedOutputStream pos;    
  46. public Producer(PipedOutputStream pos) {    
  47. this.pos = pos;    
  48. }    
  49. public void run() {    
  50. int i = 8;    
  51. try {    
  52. pos.write(i);    
  53. catch (IOException e) {    
  54. e.printStackTrace();    
  55. }    
  56. }    
  57. }    
  58.   
  59. /**   
  60. * 消费者线程(与一个管道输入流相关联)   
  61.  
  62. */    
  63. class Consumer extends Thread {    
  64. private PipedInputStream pis;    
  65. public Consumer(PipedInputStream pis)    
  66. {    
  67. this.pis = pis;    
  68. }    
  69. public void run() {    
  70. try {    
  71. System.out.println(pis.read());    
  72. catch (IOException e) {    
  73. e.printStackTrace();    
  74. }    
  75. }    
### Java 线程间通信的方法和机制 Java 中的线程间通信是指多个线程通过某种方式共享数据或控制流,从而实现协同工作的过程。以下是几种常见的线程间通信方法及其工作机制。 #### 1. 使用 `wait()` 和 `notify()/notifyAll()` `Object` 类提供了三个用于线程间通信的核心方法:`wait()`、`notify()` 和 `notifyAll()`。这些方法必须在同步上下文中调用(即在 synchronized 块或方法中)。 - **`wait()`**: 当前线程进入等待状态,直到其他线程调用了同一对象上的 `notify()` 或 `notifyAll()` 方法。 - **`notify()`**: 随机唤醒一个正在此对象上等待的单个线程。 - **`notifyAll()`**: 唤醒在此对象上等待的所有线程。 这种方法适用于生产者消费者模式等场景[^1]。 ```java class SharedResource { private int data; private boolean available = false; public synchronized void produce(int value) throws InterruptedException { while (available) { wait(); // 如果资源不可用,则当前线程等待 } data = value; available = true; notifyAll(); // 通知消费线程可以继续运行 } public synchronized int consume() throws InterruptedException { while (!available) { wait(); // 如果资源不可用,则当前线程等待 } available = false; notifyAll(); // 通知生产线程可以继续运行 return data; } } ``` --- #### 2. 使用 `Lock` 和条件变量 除了传统的 `synchronized` 关键字外,还可以使用更高层次的锁机制——`ReentrantLock` 及其关联的条件队列 (`Condition`) 来实现线程间通信。这种方式更加灵活,允许指定不同的条件进行信号传递[^3]。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class SharedResourceWithLock { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private int data; private boolean available = false; public void produce(int value) throws InterruptedException { lock.lock(); try { while (available) { condition.await(); // 生产线程等待 } data = value; available = true; condition.signalAll(); // 唤醒消费线程 } finally { lock.unlock(); } } public int consume() throws InterruptedException { lock.lock(); try { while (!available) { condition.await(); // 消费线程等待 } available = false; condition.signalAll(); // 唤醒生产线程 return data; } finally { lock.unlock(); } } } ``` --- #### 3. 利用阻塞队列 Java 的 `java.util.concurrent` 包提供了一系列高效的线程安全集合类,其中最常用的便是阻塞队列(Blocking Queue),如 `LinkedBlockingQueue` 和 `ArrayBlockingQueue`。这类容器本身实现了生产和消费逻辑中的线程协调功能[^2]。 ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumerExample { static BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10); public static class Producer implements Runnable { @Override public void run() { try { for (int i = 0; i < 20; i++) { System.out.println("Producing " + i); queue.put(i); // 自动处理满队列的情况 Thread.sleep(100); } } catch (InterruptedException e) {} } } public static class Consumer implements Runnable { @Override public void run() { try { while (true) { Integer item = queue.take(); // 自动处理空队列的情况 System.out.println("Consumed " + item); if (item == 19) break; // 终止条件 } } catch (InterruptedException e) {} } } public static void main(String[] args) throws Exception { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); producerThread.join(); consumerThread.join(); } } ``` --- #### 4. 使用原子变量 对于简单的计数器操作或其他轻量级需求,可以直接利用 `AtomicInteger`、`AtomicLong` 等原子类完成无锁化的线程间通信。 ```java import java.util.concurrent.atomic.AtomicInteger; public class AtomicCounter { private AtomicInteger counter = new AtomicInteger(0); public int incrementAndGet() { return counter.incrementAndGet(); // 完成自增并返回新值 } public int get() { return counter.get(); // 获取当前值 } } // 测试代码省略... ``` --- #### 5. 使用 `CountDownLatch`, `CyclicBarrier` 和 `Semaphore` 这些工具类分别适合不同类型的线程协作场景: - **`CountDownLatch`**: 让某个线程等待若干事件完成后才继续执行。 - **`CyclicBarrier`**: 多个线程到达屏障后再一起向前推进。 - **`Semaphore`**: 控制同时访问某资源的最大线程数量。 示例代码如下: ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is done."); latch.countDown(); // 减少倒计数值 }).start(); } latch.await(); // 主线程会一直等到计数归零 System.out.println("All threads have finished their work."); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值