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();
          }
         }
         
        }
       });
      }
     
     }
    }

  • 相关阅读:
    组队竞赛--全国模拟(三)
    排序子序列--全国模拟(三)
    20、剑指offer--包含min函数的栈
    19、剑指offer--顺时针打印链表
    leetcode链表--12、remove-duplicates-from-sorted-list-ii(删除排序链表中全部的重复结点)
    qq客服代码
    百度翻译API
    .net如何判断网页是否由搜索引擎蜘蛛访问?
    Kibana4学习<三>
    Kibana4学习<二>
  • 原文地址:https://www.cnblogs.com/youliang/p/3508504.html
Copyright © 2011-2022 走看看