Java多线程编程-同步方法

来源:互联网 发布:网络摄像头 编辑:程序博客网 时间:2024/06/04 20:53

同步方法:

将操作共享数据的方法声明为synchronized,即此方法为同步方法,能够保证一个方法在执行此方法时,其他线程在外等待,直到此线程结束。

public class Window2 implements Runnable{    int tickets = 100;//共享数据        public void run(){        while(true){            show();        }    }    public synchronized void show(){         if(ticket > 0){              try{                 Thread.currentThread().sleep(10);             }catch(InterruptedException e){                 e.printStackTrace();             }             System.out.println(Thread.currentThread().getName() + "售票,票号为" + ticket-- );         }    }}public class TestWindow{    public static void main(String[] args){         Window2 w = new Window2();        Thread t1 = new Thread(w);        Thread t2 = new Thread(w);        Thread t3 = new Thread(w);         t1.setName("窗口1");        t2.setName("窗口2");        t3.setName("窗口3");        t1.start();        t2.start();        t3.start();     }}


0 0