java多线程的创建

并发:一段时间内处理多个任务。多个任务在同一时间内切换。

并行:同一时间处理多个任务。

在java语言里提供了2种方式创建线程:

1.继承Thread类,覆盖run()方法

2.创建一个实现Runnable接口的类。使用带参数的Thread构造器来创建Thread对象。

注意开启线程要调用start()的方法,如果调用了run()方法并不是开启线程,只是执行了thread对象实例的run()方法。

线程的中断:

线程中断一般调用task.interrupt() 如果当前线程处于阻塞或等待状态,那么会抛出InterruptedExcrption 并且改成线程的中断状态,并不能终止线程的运行,如果线程不处于等待或阻塞状态,调用task.interrupt() 只会改变线程的中断状态。

测试代码:

public class Test1 {
   
    public static void main(String[] args) throws Exception{
        Thread thread = new Thread(new Runnable() {     
            @Override
            public void run() {
               try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {

                e.printStackTrace();
               
            }
                    
            }
        });
        thread.start();
        System.out.println("线程状态"+thread.isInterrupted());
        thread.interrupt();
        System.out.println("线程状态"+thread.isInterrupted());
       
        
    }
    
    
}

     打印结果:

线程状态false
线程状态true
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at com.study.one.Test1$1.run(Test1.java:12)
    at java.lang.Thread.run(Thread.java:745)
 

public class Test2 {
    public static void main(String[] args) throws Exception{
        Thread thread = new Thread(new Runnable() {     
            @Override
            public void run() {
             System.out.println("开始执行线程");
             long count = 0;
             while(count<10000000){
                 count ++;
             }
             System.out.println("线程执行结束");
                    
            }
        });
        thread.start();
        System.out.println("线程状态"+thread.isInterrupted());
        thread.interrupt();
        System.out.println("线程状态"+thread.isInterrupted());
       
        
    }
    
}

打印结果:

线程状态false
开始执行线程
线程状态true
线程执行结束

猜你喜欢

转载自blog.csdn.net/hyhanyu/article/details/81218393