线程(一)

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的时候,哪个线程调用,哪个线程就会阻塞等待,直到对应的线程执行完毕为止

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值