thread类创建线程的写法:
1.创建子类,继承自thread
2.创建一个类,实现runnable接口,再创建runnable实例传给thread实例
//Runnable在描述一个任务
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("哈哈哈");
}
}
public class BinaryTree {
public static void main(String[] args) {
Thread t=new Thread(new MyRunnable());
t.start();
}
}
3.使用匿名内部类
创建一个匿名内部类,继承自thread,再new这个匿名内部类的实例
public class BinaryTree {
public static void main(String[] args) {
//匿名内部类的写法
Thread t=new Thread(){
@Override
public void run() {
super.run();
}
};
t.start();
}
}
new的runnable,针对这个创建匿名内部类,同时new出的runnable实例传给thread构造方法
public class BinaryTree {
public static void main(String[] args) {
//匿名内部类的写法
Thread t=new Thread(new Runnable() {
@Override
public void run() {
}
});
t.start();
}
}
5.使用lambda表达式:
public class BinaryTree {
public static void main(String[] args) {
Thread t=new Thread(()->{
System.out.println("hello");
});
t.start();
}
}
在写一个比较长的整数常量的时候,可以通过_来进行分隔
并行执行的时候,程序的效果才有显著提升
在jconsole里面看到进程的状态
sun开头的是jconsole本身,org开头的是idea
start是一个特殊的方法,内部会在系统 里面创建线程;
run单纯是一个普通方法,描述了任务的内容,只是在main线程里面调用run,没有创建新线程;
中断线程
让线程对应的run执行完就能让线程停下来(特殊的是main方法执行完了,线程就完了)
1.手动设置标志位(自己创建变量),来控制线程结束
在其他线程中控制这个标志位,就可以影响这个线程
package Thread;
public class Demo1 {
private static boolean isQuit=false;
public static void main(String[] args) throws InterruptedException{
final String thread11 = "thread11";
Thread t=new Thread(()->{
while (!isQuit){
System.out.println("thread11");
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"thread11");
t.start();
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
isQuit=true;
System.out.println("终止线程");
}
}
2.更好的方法,使用thread中内置的一个标志位来进行判定:
Thread.interrupted() 这是一个静态的方法
THread.currentThread().isInterrupted() 这是实例方法,其中currentThread能获取当前线程实例
等待线程:
join():调用join的时候,哪个线程调用,哪个线程就会阻塞等待,直到对应的线程执行完毕为止