Java线程可以执行你写的程序,当你执行main()
函数时,JVM会替你创建一个main线程来执行你的程序。
Java线程其实也是对象,我们可以在main()
函数中创建一个Thread
对象并启动它,这样当main线程在执行时,便会创建另一个线程。
如何创建并启动Java线程
public class JavaThreadTest {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
}
}
当我们创建一个Thread
对象并调用它的start()
方法时,我们便启动了一个线程。但是上面这个例子中,我们没有指定这个新的线程需要执行的代码,因此在启动后,这个线程便会马上停止。
如何指定线程需要执行的代码,一般来说有两种方法:
继承Thread
继承Thread
,并重写它的run()
方法,在run
方法中指定要执行的代码。
public class JavaThreadTest {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
System.out.println("main thread");
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("new thread");
}
}
实现Runnable
实现Runnable
接口,实现它的run()
方法,并将Runnable
对象作为参数传给Thread
的构造器。
public class JavaThreadTest {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
System.out.println("main thread");
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("runnable thread");
}
}
暂停线程
通过调用Thread.sleep()
,可以让线程暂停。
try {
Thread.sleep(10L * 1000L); //暂停10秒
} catch (InterruptedException e) {
e.printStackTrace();
}
停止线程
虽说Thread
有提供stop()
方法来停止线程,但是stop()
方法并不提供任何保证,也就是当你停止线程的时候,我们并不知道线程所操作的对象的状态时怎么样的,这可能会引发许多意想不到的问题。
但我们可以自己给Runnable
提供一个新的doStop
方法,来实现停止线程。
public class StopThread {
public static void main(String[] args) {
CanStopRunnable r = new CanStopRunnable();
Thread t = new Thread(r);
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.doStop();
}
}
class CanStopRunnable implements Runnable {
private boolean isStop = false;
@Override
public void run() {
while (keepRunning()) {
System.out.println("running...");
}
}
public boolean keepRunning() {
return !isStop;
}
public synchronized void doStop() {
this.isStop = true;
System.out.println("stop!");
}
}
参考:http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html