共享变量(基本数据类型的数据)

    xiaoxiao2025-05-30  15

    /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package thread; import java.util.ArrayList; import java.util.List; public class MyStack { private List list = new ArrayList (); public synchronized void push(String value) { synchronized (this) { list.add(value); notifyAll(); } } public synchronized String pop() throws InterruptedException { synchronized (this) { if (list.size() <= 0) { //while wait(); } return list.remove(list.size() - 1); } } public static void main(String[] args) { final MyStack data = new MyStack(); Thread t2 = new Thread("C pop") { public void run() { try { while (true) { System.out.println("C pop"); data.pop(); Thread.sleep(100); } } catch (InterruptedException ex) { ex.printStackTrace(); } } }; t2.start(); t2.setPriority(5); / Thread t3 = new Thread("B pop") { public void run() { try { while (true) { System.out.println("B pop"); data.pop(); Thread.sleep(100); } } catch (InterruptedException ex) { ex.printStackTrace(); } } }; t3.start(); t3.setPriority(4); try { Thread.sleep(1000); } catch (InterruptedException ex) { } Thread t = new Thread("A push") { public void run() { while (true) { try { System.out.println("A push"); data.push("111"); Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }; t.start(); t.setPriority(1); } }
    转载请注明原文地址: https://ju.6miu.com/read-1299425.html
    最新回复(0)