有关Java线程机制的浅析

开发 后端
本文是Java线程机制的相关内容,讲述了线程的基本概念、线程的创建和启动、线程控制的基本方法和线程同步四个方面的内容。

一 线程的基本概念:
线程是一个程序内部的顺序控制流,一个进程相当于一个任务,一个线程相当于一个任务中的一条执行路径。多进程:在操作系统中能同时运行多个任务(程序);多线程:在同一个应用程序中有多个顺序流同时执行;Java线程是通过java.lang.Thread类来实现的;VM启动时会有一个由主方法(public static void main(){})所定义的线程;以通过创建Thread的实例来创建新的线程
每个线程都是通过某个特定Thread对象所对应的方法run()来完成其操作的,方法run()称为线程体
通过调用Thread类的start()方法来启动一个线程

二 Java线程的创建和启动:
可以有两种方式创建新的线程:
第一种:
     1.定义线程类实现Runnable接口
     2.Thread myThread = new Thread(target);   //target为Runnable接口类型
     3.Runnable中只有一个方法:public void run();用以定义线程运行体
     4.使用Runnable接口可以为多个线程提供共享的数据
     5.在实现Runnable接口的类的run()方法定义中可以使用Thread的静态方法public static Thread currentThread();获取当前线程的引用
   
第二种:
      1.可以定义一个Thread的子类并重写其run方法如:
          class MyThread extends Thread {   
              public void run() {...}
            
          }   
     2.然后生成该类的对象:
         MyThread myThread = new MyThread();

三 Java线程控制的基本方法:
isAlive():判断线程是否还"活"着
getPriority():获得线程的优先级数值
setPriority():设置线程的优先级数值
Thread.sleep():将当前线程睡眠指定毫秒数
join():调用某线程的该方法,将当前线程与该线程"合并",即等待该线程结束,再恢复当前线程的运行
yield():让出cpu,当前线程进入就绪队列等待调度
wait():当前线程进入对象的wait pool
notify()/notifyAll():唤醒对象的wait pool中的一个/所有等待线程

四 线程同步:
实现生产者消费者问题来说明线程问题,举例如下所示:

  1. /**  
  2. * 生产者消费者问题  
  3. */ 
  4. package com.basic.thread;  
  5.  
  6. /**  
  7. * @author johnston678  
  8. *  
  9. * @version 2009-05-06  
  10. */ 
  11. public class ProducerConsumer {  
  12.  
  13.      /**  
  14.       * @param args  
  15.       */ 
  16.      public static void main(String[] args) {          
  17.          ProductBox pb = new ProductBox();  
  18.          Producer p = new Producer(pb);  
  19.          Consumer c = new Consumer(pb);  
  20.           
  21.          Thread pThread = new Thread(p);  
  22.          Thread cThread = new Thread(c);  
  23.          pThread.setPriority(Thread.MAX_PRIORITY);  
  24.           
  25.          pThread.start();  
  26.          cThread.start();  
  27.      }  
  28.  
  29. }  
  30.  
  31. /**  
  32. * 产品对象  
  33. * @author johsnton678  
  34. */ 
  35. class Product {  
  36.      int id;  
  37.  
  38.      public Product(int id) {  
  39.          super();  
  40.          this.id = id;  
  41.      }  
  42.       
  43.      public String toString(){  
  44.          return "Product:" + id;  
  45.      }  
  46. }  
  47.  
  48. /**  
  49. * 产品盒对象  
  50. * @author johnston678  
  51. */ 
  52. class ProductBox {  
  53.  
  54.      Product[] productbox = new Product[6];  
  55.      int index = 0;  
  56.      public ProductBox() {  
  57.          super();          
  58.      }  
  59.       
  60.      public synchronized void push(Product p) {  
  61.          while (index == productbox.length) {  
  62.              try {  
  63.                  this.wait();  
  64.              } catch (InterruptedException e) {  
  65.                  // TODO Auto-generated catch block  
  66.                  e.printStackTrace();  
  67.              }  
  68.          }  
  69.          this.notify();          
  70.          productbox[index] = p;  
  71.          index ++;  
  72.      }  
  73.       
  74.      public synchronized Product pop() {  
  75.          while (index == 0) {  
  76.              try {  
  77.                  this.wait();  
  78.              } catch (InterruptedException e) {  
  79.                  // TODO Auto-generated catch block  
  80.                  e.printStackTrace();  
  81.              }  
  82.          }  
  83.          this.notify();  
  84.          index --;  
  85.          return productbox[index];  
  86.           
  87.      }  
  88. }  
  89.  
  90. /**  
  91. * 生产者  
  92. * @author johnston678  
  93. */ 
  94. class Producer implements Runnable {  
  95.  
  96.      ProductBox productbox = null;  
  97.       
  98.      public Producer(ProductBox productbox) {  
  99.          super();  
  100.          this.productbox = productbox;  
  101.      }  
  102.  
  103.      @Override 
  104.      public void run() {  
  105.          // TODO Auto-generated method stub  
  106.          for (int i=0; i<10; i++) {  
  107.              Product p = new Product(i);  
  108.              productbox.push(p);  
  109.              System.out.println("produce:" + p);  
  110.               
  111.              try {  
  112.                  Thread.sleep((int)(Math.random() * 200));  
  113.              } catch (InterruptedException e) {  
  114.                  e.printStackTrace();  
  115.              }  
  116.          }  
  117.      }  
  118.       
  119. }  
  120.  
  121. /**  
  122. * 消费者  
  123. * @author johnston678  
  124. */ 
  125. class Consumer implements Runnable {  
  126.  
  127.      ProductBox productbox = null;  
  128.       
  129.      public Consumer(ProductBox productbox) {  
  130.          super();  
  131.          this.productbox = productbox;  
  132.      }  
  133.  
  134.      @Override 
  135.      public void run() {  
  136.          // TODO Auto-generated method stub  
  137.          for (int i=0; i<10; i++) {  
  138.              Product p = productbox.pop();  
  139.              System.out.println("consume:" + p);  
  140.               
  141.              try {  
  142.                  Thread.sleep((int)(Math.random() * 1000));  
  143.              } catch (InterruptedException e) {  
  144.                  e.printStackTrace();  
  145.              }  
  146.          }  
  147.      }  
  148.       

 

【编辑推荐】

  1. 20个开发人员非常有用的Java功能代码
  2. 走进Java 7中的模块系统
  3. JavaFX 1.2 已经发布 主要新功能一览
  4. 2009年十大Java技术解决方案
  5. 2008最值得学习的五种JAVA技术
责任编辑:仲衡 来源: 小川个人博客
相关推荐

2009-06-23 14:15:00

Java垃圾回收

2009-06-11 11:17:59

Java多线程

2014-08-13 10:41:08

linux线程

2009-04-27 13:15:04

多线程方法run()

2015-08-24 14:59:06

Java线程

2016-01-08 10:06:52

2011-05-19 10:57:45

DNSSEC密钥加密

2021-08-30 09:44:47

Kubelet机制驱逐

2009-07-16 09:54:44

LookupEventSwing线程

2017-04-12 11:46:46

前端浏览器渲染机制

2023-07-07 10:41:00

Javajar文件

2015-08-03 09:54:26

Java线程Java

2009-07-02 09:38:17

Hibernate延时

2009-10-16 10:20:37

Python的GIL

2011-11-23 10:09:19

Java线程机制

2009-07-03 17:18:34

Servlet多线程

2023-06-23 15:22:28

JettyJava

2022-06-01 16:01:58

MySQL内存管理系统

2009-07-15 16:03:26

Swing线程

2010-02-01 17:25:09

Python多线程
点赞
收藏

51CTO技术栈公众号