zoukankan      html  css  js  c++  java
  • 线程笔记

    1.java中有Thread 和 Runnable两种实现线程的方式。

     

    package thread;

    public class MyThread extends Thread{
     private String name;
     private int tick = 10;
     public MyThread(String name){
      this.name = name;
     }
     public void run (){
      for(int i = 1;i <= tick;i ++){
       System.out.println("线程开始:"+this.name+" " +i);
      }
     }
     
     public static void main(String[] args) {
      MyThread t1 = new MyThread("线程A");
      MyThread t2 = new MyThread("线程B");
      MyThread t3 = new MyThread("线程C");
    //  t1.run();
    //  t2.run();
      t1.start();
      t2.start();
      t3.start();
     }
    }

    package thread;
    public class MyRunnable implements Runnable{
     private String name;
     private int tick = 10;
     public MyRunnable(String name){
      this.name = name;
     }
     public void run() {
      
      for(int i = 0;i < 20 ;i ++){
       if(tick>0)
       System.out.println(this.name + tick--);
      }
     }
     public static void main(String[] args) {
      MyRunnable mr1 = new MyRunnable("A");
     // MyRunnable mr2 = new MyRunnable("B");
      mr1.run();
     // mr2.run();
      new Thread(mr1).start();
      new Thread(mr1).start();
      new Thread(mr1).start();
     }
    }

    线程池:

    package thread;

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    public class ExecuteServiceTest {
     public static void main(String[] args) {
      ExecutorService threadPool = Executors.newCachedThreadPool();
      /**
       * 缓存线程池
       */
      for(int i = 0;i < 10;i ++){
       threadPool.execute(new Runnable(){
        
        public void run(){
         for(int i = 0;i < 10;i ++){
          System.out.println(Thread.currentThread().getName());
          
          try {
           Thread.sleep(20);
          } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
         }
         
        }
       });
      }
     
     }
    }

  • 相关阅读:
    C#生成MD5的方法
    平常心是道
    Android 三种动画的使用 – Tween Animation
    17个Javascript日期选择器
    Javascript解码编码常用函数
    mysql 命令行导入导出数据
    技术驱动还是产品驱动
    Ubuntu 和 Redhat / Fedora 服务管理命令对比表
    jquery常用技巧
    Fedora 17安装JDK1.7
  • 原文地址:https://www.cnblogs.com/youliang/p/3508504.html
Copyright © 2011-2022 走看看