同步方法解决线程安全问题

使用同步方法解决线程安全问题

实现接口的同步方法实例

package A_ShangGuiGu.Thread.ThreadDemo;

/**
* 使用同步方法解决Runnable接口的线程安全问题。
* 将需要对代码进行的操作全部放入一个方法中,在方法名前使用synchronized字段来将该方法定义为同步方法。
* 同步方法的总结:
* 1.同步方法依然涉及到同步监视器,只是同步监视器不需要显示的声明
* 2.非静态的同步方法,它的同步监视器:this:(当前对象)
*   静态同步方法的同步监视器是当前类本身。name.class
*/

class MaiPiao2 implements Runnable{
   private int chepiao = 100;
   Object obj = new Object();
   @Override
   public void run() {
       while (true) {
              show();
              if (chepiao==0){
                  break;
              }
      }

  }
   private synchronized void show (){
       if (chepiao > 0) {
           try {
               Thread.sleep(1);
          } catch (InterruptedException e) {
               throw new RuntimeException(e);
          }
           System.out.println(Thread.currentThread().getName() + ":" + chepiao);
           chepiao--;
      }
  }
}
public class ThreadWindowTest2 {
   public static void main(String[] args) {
       MaiPiao2 maiPiao2 = new MaiPiao2();
       Thread t1 = new Thread(maiPiao2);
       Thread t2 = new Thread(maiPiao2);
       Thread t3 = new Thread(maiPiao2);

       t1.setName("窗口1");
       t2.setName("窗口2");
       t3.setName("窗口3");

       t1.start();
       t2.start();
       t3.start();
  }
}

继承的线程的同步方法使用实例

package A_ShangGuiGu.Thread.ThreadDemo;

class Window3 extends Thread{
   private static int chepiao = 100;

   @Override
   public void run() {
       while(true){
           show();
           if (chepiao==0){
               break;
          }
      }
  }
   private static synchronized void show (){
       if (chepiao > 0) {
           try {
               Thread.sleep(10);
          } catch (InterruptedException e) {
               throw new RuntimeException(e);
          }
           System.out.println(Thread.currentThread().getName() + ":" + chepiao);
           chepiao--;
      }
  }
}
public class ThreadWindowTest3 {
   public static void main(String[] args) {

       Window3 t1 = new Window3();
       Window3 t2 = new Window3();
       Window3 t3 = new Window3();

       t1.setName("窗口1");
       t2.setName("窗口2");
       t3.setName("窗口3");

       t1.start();
       t2.start();
       t3.start();
  }
}
 
posted @ 2022-10-23 00:38  zhazhawei906  阅读(188)  评论(0)    收藏  举报