有关Java线程机制的浅析
创始人
2024-04-01 16:12:16
0

一 线程的基本概念:
线程是一个程序内部的顺序控制流,一个进程相当于一个任务,一个线程相当于一个任务中的一条执行路径。多进程:在操作系统中能同时运行多个任务(程序);多线程:在同一个应用程序中有多个顺序流同时执行;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技术

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...