声明:该博客参考https://www.cnblogs.com/kaituorensheng/p/10079916.html,感谢哥们。
1、Sync.java
package com.cn.commodity.config; public class Sync { public synchronized void test() { System.out.println("test start"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test end"); } }
2、MyThread2.java
package com.cn.commodity.config; public class MyThread2 extends Thread { public Sync sync; MyThread2(Sync sync) { this.sync = sync; } @Override public void run() { System.out.println("hi...."); sync.test(); } public static void main(String[] args) { Sync sync = new Sync(); for (int i = 0; i < 3; ++i) { Thread thread = new MyThread2(sync); thread.start(); } } }
当请求过来时,可以将要执行的内容放在test方法中,这样就实现了串行执行。因为线程使用同一个sync对象。