Java 多线程------解决 实现继承 Thread类 方式线程的线程安全问题 方式二:同步方法
作者:互联网
1 package bytezero.threadsynchronization; 2 3 4 5 /** 6 * 使用同步方法解决实现 继承 Thread类 的线程安全问题 7 * 8 * 9 * 10 * @author Bytezero1·zhenglei! Email:420498246@qq.com 11 * create 2021-10-17 16:38 12 */ 13 class WindowM extends Thread{ 14 private static int ticket = 100; 15 16 @Override 17 public void run() { 18 while (true){ 19 20 show(); 21 } 22 } 23 24 private static synchronized void show(){ //同步监视器:WindowM.class 25 // private synchronized void show(){ //同步监视器: w1 w2 w3 此种解决方式是错误的 26 if(ticket > 0){ 27 try { 28 Thread.sleep(100); 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 System.out.println(Thread.currentThread().getName() + ":卖票,票号为:"+ticket); 33 ticket--; 34 } 35 } 36 37 } 38 39 40 public class WindowMethod { 41 public static void main(String[] args) { 42 WindowM w1 = new WindowM(); 43 WindowM w2 = new WindowM(); 44 WindowM w3 = new WindowM(); 45 46 w1.setName("窗口1"); 47 w2.setName("窗口2"); 48 w3.setName("窗口3"); 49 50 w1.start(); 51 w2.start(); 52 w3.start(); 53 54 } 55 56 }
........
标签:Java,w1,Thread,void,线程,w2,WindowM,ticket,多线程 来源: https://www.cnblogs.com/Bytezero/p/15417481.html