zoukankan      html  css  js  c++  java
  • java线程以及定时任务

    线程的概念在此不再赘述。

    下面介绍三种启动线程的方式。

    1. 继承Thread

    public class ThreadTest extends Thread {
    
        @Override
        public void run() {
            int i  = 0;
            while (i < 10){
                i++;
                System.out.println("this is Thread thread");
            }
    
        }
    }

    调用

    ThreadTest threadTest = new ThreadTest();
    threadTest.start();

    2. 实现Runnable接口

    public class RunnableTest implements Runnable{
    
        int a;
        int b;
    
        public RunnableTest(int a, int b){
            this.a = a;
            this.b = b;
        }
        public void run(){
            int i = 0;
            while (i < 10){
                i++;
                System.out.println("a:" + a + " b:" +b);
            }
        }
    }

    调用

    RunnableTest threadExtends2 = new RunnableTest(5,6);
    new Thread(threadExtends).start();

    3. 匿名类

    Thread t = new Thread(){
              public void run(){
                  int i = 0;
                  while (i < 10){
                      i++;
                      System.out.println("this is Inside Thread");
                 }
              }
    };
    t.start()

    线程常用方法:

    1. sleep    线程暂停,睡会再执行。

    2. join    加入到当前线程中,若加入,则先执行加入的线程,后执行当前线程。

    3. setPriority    设置线程优先级。

    4. yield    临时暂停。

    下面介绍一种定时执行任务的方法,用的是TimerTask

    public static void main(String args[]){
            Timer t = new Timer();
            TimerTask timerTask = new TimerTask() {
                int i = 0;
                @Override
                public void run() {
                    System.out.println(i);
                    i++;
                    if (i == 5)
                        t.cancel();
                }
            };
            t.scheduleAtFixedRate(timerTask,0,1500);
  • 相关阅读:
    [BZOJ2809][Apio2012]dispatching
    [BZOJ4584][Apio2016]赛艇
    [BZOJ3206][Apio2013]道路费用
    [codeforces551E]GukiZ and GukiZiana
    [BZOJ3809]Gty的二逼妹子序列
    [BZOJ3289]Mato的文件管理
    [BZOJ3052][UOJ#58][WC2013]糖果公园
    [SPOJ10707]Count on a tree II
    [BZOJ1086][SCOI2005]王室联邦
    python小知识
  • 原文地址:https://www.cnblogs.com/NoYone/p/8325812.html
Copyright © 2011-2022 走看看