done like this:html
Thread thread = new Thread();
thread.start();
复制代码
public MyThread extends Thread{
@Override
public void run() {
System.out.println("Hello, World!");
}
}
复制代码
public MyRunnable implements Runnable{
public void run() {
System.out.println("all so have to say hello, world!");
}
}
复制代码
Runnable myRunnable = new Runnable() {
public void run() {
System.out.println("Hello, World!");
}
};
复制代码
Runnable myRunable = {
System.out.println("Hello, World!");
};
复制代码
经过实现接口的方式,可以让代码书写更加精简。能够经过Lambda来简化代码。实现接口的方式可以有效分离业务逻辑与线程运行代码,能让线程池有效管理和调度任务,在线程池繁忙时进入队列等待线程池调度。这种方式可以迎合工做者模型。java
有时候能够结合两种方式来使用,最典型的表明就是实现一个线程池。多线程
Thread newThread = new Thread(MyRunnable());
newThread.run(); //should be start();
复制代码
仅执行run方法,并不会建立新的线程,而是在本线程来执行run方法里面的业务逻辑。切记建立一个新的线程,必定要执行start方法而非run方法。jvm
每每为了区分哪一个线程在运行,会经过System.out的方式来打印线程名称。经过继承Thread的方式能够直接经过Thread的getName方法来打印名称。经过实现的方式并无getName方法,此时能够经过Thread的静态方法currentThread来取得当前线程引用。ide
在建立线程时,能够经过Thread的构造方法传递线程名称;post
Thread myThread = new Thread("our-thread0") {
@Override
public void run() {
System.out.println("run by: " + getName());
}
};
Runnable myRunnable = () -> {
final Thread currentThread = Thread.currentThread();
System.out.println("run by: " + currentThread.getName());
};
myThread.start();
new Thread(myRunnable, "our-thread1").start();
复制代码
public class ThreadExample {
private static void startThread(int i) {
new Thread("thread: " + i) {
@Override
public void run() {
System.out.println(getName() + " running.");
}
}.start();
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
IntStream.range(0, 10)
.forEach(ThreadExample::startThread);
}
}
复制代码
如你所见,以上实例中,顺序建立并执行10个线程,但线程的运行并不必定是顺序,此时10个线程是并行执行的,线程的执行顺序是由jvm和操做系统共同决定的。this
try {
// 当前线程睡眠 10 s
Thread.sleep(10L * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
复制代码
能够经过Thread.sleep()方法,经过传递毫秒数来暂停线程。暂停时长以传递毫秒数为准。spa
Thread对象中默认包含了stop(),pause()等方法。但已经被废弃了,默认的stop()方法并不能保证线程在何种状态下被中止。这意味着,全部被线程访问到的java对象都将在一个未知的状态下运行。若是其余线程须要访问相同的对象,那么你的应用将会出现不可预测的失败。操作系统
public class ThreadStopExample implements Runnable {
// 是否中止
private boolean doStop = false;
// 继续运行线程
public synchronized boolean keepRunning() {
return !doStop;
}
// 中止线程
public synchronized void stop() {
this.doStop = true;
}
@Override
public void run() {
while (keepRunning()) {
System.out.println("Running");
try {
// 暂停 3 s
Thread.sleep(3L * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final ThreadStopExample threadStopExample = new ThreadStopExample();
new Thread(threadStopExample, "our thread").start();
try {
// 10 s 后中止线程
Thread.sleep(10L * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadStopExample.stop();
}
}
复制代码
该系列博文为笔者复习基础所著译文或理解后的产物,复习原文来自Jakob Jenkov所著Java Concurrency and Multithreading Tutorial 线程