小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java多线程

发布者: 小白教程

以下代码显示了如何在程序中运行多线程。

  1. public class Main {
  2. public static void main(String[] args) {
  3. // Create two Thread objects
  4. Thread t1 = new Thread(Main::print);
  5. Thread t2 = new Thread(Main::print);
  6. // Start both threads
  7. t1.start();
  8. t2.start();
  9. }
  10. public static void print() {
  11. for (int i = 1; i <= 500; i++) {
  12. System.out.println(i);
  13. }
  14. }
  15. }

上面的代码生成以下结果。

线程同步

Java编程语言内置了两种线程同步:

  • 互斥同步
  • 条件同步

在互斥同步中,在一个时间点只允许一个线程访问代码段。

条件同步通过条件变量和三个操作来实现:等待,信号和广播。


同步关键字

synchronized关键字用于声明需要同步的关键部分。

有两种方法可以使用synchronized关键字:

  • 将方法声明为关键部分
  • 将语句块声明为关键段

我们可以通过在方法的返回类型之前使用关键字synchronized来声明一个方法作为临界段。

  1. public class Main {
  2. public synchronized void someMethod_1() {
  3. // Method code goes here
  4. }
  5. public static synchronized void someMethod_2() {
  6. // Method code goes here
  7. }
  8. }

我们可以声明一个实例方法和一个静态方法同步。构造函数不能声明为同步。

以下代码说明了使用关键字synchronized:

  1. public class Main {
  2. public synchronized void someMethod_1() {
  3. // only one thread can execute here at a time
  4. }
  5. public void someMethod_11() {
  6. synchronized (this) {
  7. // only one thread can execute here at a time
  8. }
  9. }
  10. public void someMethod_12() {
  11. // multiple threads can execute here at a time
  12. synchronized (this) {
  13. // only one thread can execute here at a time
  14. }
  15. // multiple threads can execute here at a time
  16. }
  17. public static synchronized void someMethod_2() {
  18. // only one thread can execute here at a time
  19. }
  20. public static void someMethod_21() {
  21. synchronized (Main.class) {
  22. // only one thread can execute here at a time
  23. }
  24. }
  25. public static void someMethod_22() {
  26. // multiple threads can execute here at a time
  27. synchronized (Main.class) {
  28. // only one thread can execute here at a time
  29. }
  30. // multiple threads can execute here at a time
  31. }
  32. }

12下一页
上一篇:Java 10 新特性下一篇:Java TCP服务器

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:40 , Processed in 0.020488 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部