线程创建
线程的创建有5种方法分别是:
1.继承Thread类,重写run方法;
2.实现接口Runnable,重写run方法;
3.继承Thread类,用匿名内部类重写run方法;
4.实现Runnable类,用匿名内部类重写run方法;
5.使用lambda表达式
1.继承Thread类,重写run方法;
class MyThread extends Thread{
public void run(){
try {
while (true){
System.out.println("hello thread");
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test1 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
System.out.println("hello main");
}
}
2.实现接口Runnable,重写run方法;
class MyRunnable implements Runnable {
public void run(){
try {
System.out.println("hello runnable");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test2 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
System.out.println("hello main");
}
}
3.继承Thread类,用匿名内部类重写run方法;
public class Test3 {
public static void main(String[] args) {
Thread t = new Thread(){
public void run(){
System.out.println("hello thread");
}
};
t.start();
System.out.println("hello main");
}
}
4.实现Runnable类,用匿名内部类重写run方法;
public class Test4 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello thread");
}
});
t.start();
System.out.println("hello main");
}
}
5.使用lambda表达式;
public class Test5 {
public static void main(String[] args) {
Thread t = new Thread(()->{
System.out.println("hello Thread");
});
System.out.println("hello main");
t.start();
}
}
线程中断
使用 Thread.interrupted() 或者Thread.currentThread().isInterrupted() 代替自定义标志位.
public void interrupt() | 中断对象关联的线程 |
public static boolean interrupted() | 判断当前线程的中断标志位是否设置 |
public boolean isInterrupted() | 判断对象关联的中断标志位是否设置 |
线程等待
有时我们需要一个线程等待另一个线程完成再进行下一步工作,那么此时我们就需要用到方法 join()。
举个例子,现在有两个线程 t1 和 t2,我们需要 t1 完成了在运行 t2;那么我们就需要在 t2 中加上代码 t1.join(); t1 在 t2 引用 join(),因此 t2 需要等待 t1 先完成;
public void join() | 等待线程结束 |
public void join(long millis) | 等待线程结束,最多等待millis毫秒 |
public void join(long millis,int nanos) | 等待线程结束,但精度更高,可以精确到纳秒 |
线程休眠
使用 sleep(long millis) 让此线程进入休眠状态 millis 毫秒,当线程进入休眠状态的时候,是不会占用cpu资源的。
获取线程实例
public static Thread currentThread(); | 返回当前线程对象的引用 |
public class test3 {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println("线程名称: " + thread.getName());
}
}