首先创建线程有两种方法,
一种是通过继承Thread方法。
public class ThreadTest1 extends Thread {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ThreadTest().start();
}
}
一种是通过实现Runnable的接口
public class RunnalbleTest implements Runnable {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ThreadTest().start();
}
}
interrupt
结束线程在调用Object类的wait方法或该类的join方法、sleep方法过程中的阻塞状态,并在调用wait、join和sleep方法处产生InterruptedException异常。
public static void main(String[] args) {
TimeThread timeThread = new TimeThread();
timeThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//interrupt提前结束了timeThread线程的阻塞状态
timeThread.interrupt();
class TimeThread extends Thread{
@Override
public void run() {
System.out.println(new Date());
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("睡醒了");
}
}
currentThread
返回当前正在执行的线程对象。即执行该方法的线程对象。
public class Test {
public static void main(String[] args) {
TimeThread timeThread = new TimeThread("线程一");
timeThread.start();
System.out.println(Thread.currentThread().getName());
System.out.println("主线程:" + timeThread.getName());
}
}
class TimeThread extends Thread{
public TimeThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println("timeThread线程:" + Thread.currentThread().getName());
}
}
join方法
执行该方法的线程进入阻塞状态,直到调用该方法的线程结束后再由阻塞转为就绪状态。
package venus;
public class Test {
public static void main(String[] args) {
TimeThread timeThread = new TimeThread();
timeThread.start();
CountThread countThread = new CountThread(timeThread);
countThread.start(); //执行一次
}
}
class CountThread extends Thread{
TimeThread timeThread;
CountThread(TimeThread timeThread) {
this.timeThread = timeThread;
}
@Override
public void run() {
for(int i = 0;i<50;i++) {
System.out.println("计数1"+i);
if(i==2) {
try {
timeThread.join(); //执行join方法的线程阻塞,直到调用join方法的线程执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class TimeThread extends Thread{
@Override
public void run() {
for(int i = 0;i<50;i++) {
System.out.println("时间2"+i);
}
}
}
timeThread.join(); //执行join方法的线程阻塞,直到调用join方法的线程执行完毕
执行timeThread方法,当timeThread方法执行完毕后,再执行countThread方法。
isAlive
判定该线程是否处于就绪、运行或阻塞状态,如果是则返回true,否则返回false。
public class Test {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
TimeThread timeThread = new TimeThread(thread);
timeThread.start();
System.out.println("############"+thread.isAlive());
}
}
class TimeThread extends Thread{
Thread thread;
TimeThread(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("@@@@@"+thread.isAlive());
}
}