21xrx.com
2024-05-20 16:45:04 Monday
登录
文章检索 我的文章 写文章
Java多线程编程实例
2023-07-11 08:16:46 深夜i     --     --
Java 多线程 编程 实例 并发编程

Java多线程编程是一种重要的编程技术,可以利用计算机的多核心处理能力,提高程序的执行效率。本文将介绍几个Java多线程编程实例,帮助读者更好地掌握这一技术。

1. 线程创建和启动

Java语言通过Thread类来创建和启动线程。以下是一个简单的例子:


public class MyThread extends Thread {

  public void run()

    //相应的线程任务

  

}

public static void main(String[] args) {

  MyThread myThread = new MyThread();

  myThread.start();

}

在例子中,MyThread类继承自Thread类,并实现了run()方法。在main()方法中,通过创建MyThread对象并调用start()方法来启动线程。

2. 线程的同步

当多个线程同时访问某一个共享资源时,可能会出现数据竞争的情况,导致程序出错。因此,需要使用同步方法或同步代码块来解决这个问题。以下是一个使用同步代码块的例子:


public class SynchronizedTest {

  private int count = 0;

  public void increase() {

    synchronized (this) {

      count++;

    }

  }

  public int getCount()

    return count;

  

}

public static void main(String[] args) {

  SynchronizedTest test = new SynchronizedTest();

  for(int i = 0; i < 10; i++) {

    new Thread(() -> {

      for(int j = 0; j < 1000; j++) {

        test.increase();

      }

    }).start();

  }

  try {

    Thread.sleep(2000);

  } catch (InterruptedException e) {

    e.printStackTrace();

  }

  System.out.println(test.getCount());

}

在例子中,SynchronizedTest类封装了一个count变量,并定义了increase()方法用来递增count。在increase()方法中,使用synchronized关键字来标记代码块,确保在同一个时刻只有一个线程可以访问该部分代码。在main()方法中已启动10个线程,分别执行1000次递增操作。最后输出count值,验证程序的正确性。

3. 线程的通信

当一个线程需要等待另一个线程完成某个任务时,需要使用线程的通信机制。Java中提供了wait()和notify()两个关键字来实现线程的通信。以下是一个简单的例子:


public class WaitNotifyTest {

  private boolean flag = false;

  public synchronized void work() {

    while(!flag) {

      try {

        wait();

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

    }

    System.out.println("worker thread is working");

  }

  public synchronized void startWork() {

    System.out.println("main thread is starting");

    flag = true;

    notify();

  }

}

public static void main(String[] args) {

  WaitNotifyTest test = new WaitNotifyTest();

  new Thread(() -> {

    test.work();

  }).start();

  try {

    Thread.sleep(2000);

  } catch (InterruptedException e) {

    e.printStackTrace();

  }

  test.startWork();

}

在例子中,WaitNotifyTest类定义了两个方法work()和startWork(),分别用于开启工作线程和通知工作线程开始工作。在work()方法中,当flag为false时,调用wait()方法来进入等待状态。在startWork()方法中,将flag置为true并调用notify()方法来通知工作线程开始工作。

以上是几个Java多线程编程实例,通过学习这些实例,可以更好地理解Java多线程编程的基本概念和技术原理。同时,在实际开发中,需要结合具体情况灵活运用多线程编程技术,提高程序的并发性和效率。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复