多线程基础知识总结一

2020-10-13  本文已影响0人  闫回
基础概念:

CPU核心数和线程数的关系 1:1,4核表示同时可以运行4个线程,使用超线程技术(1:2)4核可以运行8个线程。
我们平时开发的时候,并没有感觉到cpu核心数的限制,想启动线程就启动线程,这是因为操作系统提供了一种CPU时间片轮转机制,时间片轮转调度是一种最古老、最简单、最公平且使用最广的算法,又称RR调度,每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。

class UseThread extends Thread{
@Override
public void run(){
super.run();
//do my work
System.out.println("I am extends Thread")
}
}
//使用
UseThread useThread = new UseThread();
useThread.start();

2实现Runnable接口,交给Thread运行
class UseRun implements Runnable{
@Override
public void run(){
System.out.println("I am implements Runnable");
}
}
使用
UseRun useRun = new UseRun();
new Thread(useRun).start();

3)实现Callable接口,交给Thread运行,允许有返回值

class UseCall implements Callable<String>{
@Override
public String call() throws Exception{
System.out.println("I am implements Callable);
return "CallResult";
}
}
使用
UseCall useCall = new UseCall();
FutureTask<String> futureTask = new FutureTask<>(useCall);
new Thread(futureTask).start();
System.out.println(futureTask.get());

Thread是对线程的抽象 唯一代表线程
Runable和Callable是对任务的抽象

public class EndThread{

private static class UseThread extends Thread{
    
    public UseThread(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName+" interrrupt flag ="+isInterrupted());
        //while(!isInterrupted()){
        while(!Thread.interrupted()){
        //while(true){
            System.out.println(threadName+" is running");
            System.out.println(threadName+"inner interrrupt flag ="+isInterrupted());
        }
        System.out.println(threadName+" interrrupt flag ="+isInterrupted());
    }
}

public static void main(String[] args) throws InterruptedException {
    Thread endThread = new UseThread("endThread");
    endThread.start();
    Thread.sleep(10);
    endThread.interrupt();

}

}

public class StartAndRun {

public static class ThreadRun extends Thread{

    @Override
    public void run() {
        int i = 90;
        while(i>0){
            SleepTools.ms(1000);
            System.out.println("I am "+Thread.currentThread().getName()
                    +" and now the i="+i--);
        }
    }
}

private static class User {
    public void us() {
        
    }
}

public static void main(String[] args) {
    ThreadRun beCalled = new ThreadRun();
    beCalled.setName("beCalled");
    //beCalled.run();

    new User().us();

    beCalled.start();
}

}

上一篇 下一篇

猜你喜欢

热点阅读