zoukankan      html  css  js  c++  java
  • 多线程 编写多线程的两种方式

    1、通过继承Thread编写多线程类

     1 package org.zln.thread;
     2 
     3 import java.util.Date;
     4 
     5 /**
     6  * Created by coolkid on 2015/6/21 0021.
     7  */
     8 public class TestThread extends Thread{
     9     private int time;//休眠时间
    10     private String user;//调用用户
    11 
    12     public TestThread(int time, String user) {
    13         this.time = time;
    14         this.user = user;
    15     }
    16 
    17     @Override
    18     public void run() {
    19         while (true){
    20             try {
    21                 System.out.println(Thread.currentThread().getName()+"	"+user+" 休息 "+time+"ms-"+new Date());
    22                 Thread.sleep(time);
    23             } catch (InterruptedException e) {
    24                 e.printStackTrace();
    25             }
    26         }
    27     }
    28 
    29     public static void main(String[] args) {
    30         Thread thread1 = new TestThread(1000,"Jack");
    31         Thread thread2 = new TestThread(3000,"Mike");
    32         thread1.start();
    33         thread2.start();
    34     }
    35 }
    E:GitHub oolsJavaEEDevelopLesson1_JavaSe_Demo1srcorgzln hreadTestThread.java

    设置线程优先级:thread2.setPriority(Thread.MAX_PRIORITY);

    这样就能够保证每次都是thread2先于thread1执行

    2、通过实现Runnable接口编写多线程类

     1 package org.zln.thread;
     2 
     3 import java.util.Date;
     4 
     5 /**
     6  * Created by coolkid on 2015/6/21 0021.
     7  */
     8 public class TestRunnable implements Runnable {
     9     private int time;//休眠时间
    10     private String user;//调用用户
    11 
    12     public TestRunnable(int time, String user) {
    13         this.time = time;
    14         this.user = user;
    15     }
    16 
    17     @Override
    18     public void run() {
    19         while (true){
    20             try {
    21                 System.out.println(Thread.currentThread().getName()+"	"+user+" 休息 "+time+"ms-"+new Date());
    22                 Thread.sleep(time);
    23             } catch (InterruptedException e) {
    24                 e.printStackTrace();
    25             }
    26         }
    27     }
    28 
    29     public static void main(String[] args) {
    30         Thread t1 = new Thread(new TestRunnable(1000,"Jack"));
    31         Thread t2 = new Thread(new TestRunnable(3000,"Mike"));
    32         t2.setPriority(Thread.MAX_PRIORITY);
    33         t1.start();
    34         t2.start();
    35     }
    36 }
    E:GitHub oolsJavaEEDevelopLesson1_JavaSe_Demo1srcorgzln hreadTestThread.java
  • 相关阅读:
    各大代码托管服务器的分析比较
    《构建之法》读后
    【转】简单的程序诠释C++ STL算法系列之十五:swap
    【转】error while loading shared libraries: xxx.so.x" 错误的原因和解决办法
    C++大会感悟
    一次DDOS攻击引起的安全漫谈
    为npm设置代理,解决网络问题
    Rust 中的类型转换
    Rust 智能指针(二)
    软件设计原则
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4592347.html
Copyright © 2011-2022 走看看