?
java测试线程同步synchronized
TT.java
class="java">public class TT implements Runnable { int b = 100; public synchronized void m1() throws Exception{ //Thread.sleep(2000); b = 1000; Thread.sleep(5000); System.out.println("b = " + b); } public synchronized void m2() throws Exception { Thread.sleep(2500); b = 2000; } public void run() { try { m1(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { TT tt = new TT(); Thread t = new Thread(tt); t.start(); //t.sleep(500); tt.m2(); System.out.println(tt.b); } }
?
F:\java\Thread>javac TT.java F:\java\Thread>java TT 1000 b = 1000 F:\java\Thread>
?
生产者消费者模型wait、notify、notifyAll
/* 生产者消费者模型 */ public class ProducerConsumer { public static void main(String[] args) { //一个篮子 SyncStack ss = new SyncStack(); //生产者 Producer p = new Producer(ss); //消费者 Consumer c = new Consumer(ss); new Thread(p).start(); new Thread(c).start(); } } //窝头 class WoTou { int id; WoTou(int id) { this.id = id; } public String toString() { return "WoTou : " + id; } } //同步栈,先进后出 class SyncStack { int index = 0; //一个篮子放6个数组的窝头 WoTou[] arrWT = new WoTou[6]; //放 public synchronized void push(WoTou wt) { while(index == arrWT.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); arrWT[index] = wt; index ++; } //拿 public synchronized WoTou pop() { while(index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; return arrWT[index]; } } //生产者 class Producer implements Runnable { SyncStack ss = null; Producer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { WoTou wt = new WoTou(i); ss.push(wt); System.out.println("生产了:" + wt); try { Thread.sleep((int)(Math.random() * 200)); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者 class Consumer implements Runnable { SyncStack ss = null; Consumer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { WoTou wt = ss.pop(); System.out.println("消费了: " + wt); try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
?
F:\java\Thread>javac ProducerConsumer.java F:\java\Thread>java ProducerConsumer 生产了:WoTou : 0 消费了: WoTou : 0 生产了:WoTou : 1 生产了:WoTou : 2 生产了:WoTou : 3 生产了:WoTou : 4 生产了:WoTou : 5 生产了:WoTou : 6 消费了: WoTou : 6 生产了:WoTou : 7 消费了: WoTou : 7 生产了:WoTou : 8 消费了: WoTou : 8 生产了:WoTou : 9 消费了: WoTou : 9 生产了:WoTou : 10 消费了: WoTou : 10 生产了:WoTou : 11 消费了: WoTou : 11 生产了:WoTou : 12 消费了: WoTou : 12 生产了:WoTou : 13 消费了: WoTou : 13 生产了:WoTou : 14 消费了: WoTou : 14 生产了:WoTou : 15 生产了:WoTou : 16 消费了: WoTou : 15 消费了: WoTou : 16 生产了:WoTou : 17 生产了:WoTou : 18 消费了: WoTou : 17 消费了: WoTou : 18 生产了:WoTou : 19 消费了: WoTou : 19 消费了: WoTou : 5 消费了: WoTou : 4 消费了: WoTou : 3 消费了: WoTou : 2 消费了: WoTou : 1 F:\java\Thread>
?
?