Java 多线程(Runable)

272 阅读1分钟

大概内容

Runable是个接口。官方使用建议:

  • In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods.(不会这也要翻译吧?)

使用方法

  • 自定义实现接口Runable的类
  • 重写run()方法
  • 当通过Thread(Runnable target)构造方法创建一个线程对象时,只需该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法作为运行代码,而不需要调用Thread类中的run()方法。

用例

import java.text.SimpleDateFormat;
import java.util.Date;

public class RunableTest {
    public static void main(String[] args) {
     TTt11 t1 = new TTt11();
     TTt22 t2 = new TTt22();
     new Thread(t1).start();
     new Thread(t2).start();
    }
}
class TTt11 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程TTt11----" + new SimpleDateFormat("HH:mm:ss:SSS.SSSSS").format(new Date()));
        }
    }
}
class TTt22 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程TTt22----" + new SimpleDateFormat("HH:mm:ss:SSS.SSSSS").format(new Date()));
        }
    }
}

sleep()方法

import java.text.SimpleDateFormat;
import java.util.Date;

public class RunableTest {
    public static void main(String[] args) {
        TTt11 t1 = new TTt11();
        TTt22 t2 = new TTt22();
        new Thread(t1).start();
        new Thread(t2).start();
        System.out.println("正在运行的线程名称:main "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));
    }
}
class TTt11 implements Runnable {
    @Override
    public void run()
    {
        try
        {
            System.out.println("正在运行的线程名称:TTt11 "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"开始");
            Thread.sleep(2000);    //延时2秒
            System.out.println("正在运行的线程名称:TTt11 "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"结束");
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
class TTt22 implements Runnable {
    @Override
    public void run() {
        try
        {
            System.out.println("正在运行的线程名称:TTt22 "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"开始");
            Thread.sleep(4000);    //延时4秒
            System.out.println("正在运行的线程名称:TTt22 "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"结束");
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}