1. 使用wait()和notify()来实现线程间的同步: ```java public class MyThread { private Object lock; public MyThread(Object lock){ this.lock = lock; } public void run(){ synchronized (lock){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread is running..."); } } } public class Test { public static void main(String[] args) { Object lock = new Object(); MyThread thread1 = new MyThread(lock); thread1.start(); synchronized (lock){ lock.notify(); } } } ``` 2. 使用CountDownLatch来实现线程同步: ```java public class MyThread extends Thread{ private CountDownLatch latch; public MyThread(CountDownLatch latch){ this.latch = latch; } public void run(){ try { latch.await(); System.out.println("Thread is running..."); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(1); MyThread thread1 = new MyThread(latch); thread1.start(); latch.countDown(); } } ``` 3. 使用CyclicBarrier来实现线程同步: ```java public class MyThread extends Thread{ private CyclicBarrier barrier; public MyThread(CyclicBarrier barrier){ this.barrier = barrier; } public void run(){ try { barrier.await(); System.out.println("Thread is running..."); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } public class Test { public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(1); MyThread thread1 = new MyThread(barrier); thread1.start(); barrier.await(); } } ``` 4. 使用Semaphore来实现线程同步: ```java public class MyThread extends Thread{ private Semaphore semaphore; public MyThread(Semaphore semaphore){ this.semaphore = semaphore; } public void run(){ try { semaphore.acquire(); System.out.println("Thread is running..."); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } } public class Test { public static void main(String[] args) { Semaphore semaphore = new Semaphore(1); MyThread thread1 = new MyThread(semaphore); thread1.start(); semaphore.release(); } } ```
上一篇: 下一篇:

相关推荐

随机推荐

  1. Qoo10趣天日本广告投标助手
  2. 西西趣天采集插件2.0升级版
  3. 西西电商图片下载助手
  4. 西西趣天韩国批量上货助手最新版
  5. 西西趣天日本批量上货助手最新版
  6. HeidiSQL_12.12绿色版
  7. WPS office 10.1.0.7311精简版(无联网功能)无广告超级好用
  8. dupeGuru – 电脑重复文件查找工具,支持跨平台使用!
  9. Caesium – 图片批量压缩软件
  10. 7-Zip 免费解压软件
  11. TrayS 绿色免安装版 (任务栏美化工具)
  12. AirDroid 3.7.2.1 Android 设备管家远程控制
  13. Snipaste截图软件下载
  14. Everything 1.4.1.1026 文件搜索工具
  15. chromium浏览器伪造sni工具网页版