解决线程安全问题
作者:互联网
方式一:同步代码块
synchronized (同步监视器){
//需要被同步的代码
}
说明:
操作共享数据的代码,即为需要被同步的代码
共享数据:多个线程共同操作的变量
同步监视器:俗称,锁。任何一个类的对象都可以充当锁。(要求:多个线程必须要共用同一把锁)
public class Window implements Runnable { private int ticket = 100; private Object obj = new Object(); @Override public void run() { while (true) { synchronized (obj) { //可以用this,此时的this:唯一的Window的对象 if (ticket > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "***" + ticket); ticket--; } else { break; } } } } } class WindowTest { public static void main(String[] args) { Window w = new Window(); Thread t1 = new Thread(w);//3个线程公用1个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(); } }
public class ThreadTest { public static void main(String[] args) { Window1 t1 = new Window1(); Window1 t2 = new Window1(); Window1 t3 = new Window1(); t1.setName("线程1"); t2.setName("线程2"); t3.setName("线程3"); t1.start(); t2.start(); t3.start(); } } class Window1 extends Thread{ private static int ticket = 100; private static Object obj = new Object(); @Override public void run() { while (true) { synchronized (obj) { //可以用Window1.class,类也是对象,在内存中只加载一次 if (ticket > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "***" + ticket); ticket--; } else { break; } } } } }
标签:Thread,start,Window1,安全,线程,解决,new,ticket 来源: https://www.cnblogs.com/ixtao/p/16581534.html