如何创建多线程

Posted bigdata1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何创建多线程相关的知识,希望对你有一定的参考价值。

线程的状态

初始化—就绪—运行—终止

Sleep : 超时等待,过了一段时间就会进入就绪状态进行竞争cpu资源。

Wait: 等待状态,没有通过notify 或者 notifyAll 唤醒,就会一直进行等待。

Block: block io 或者 遇到加锁的代码时, 接受到数据或者获取到锁就会到运行状态,也有可能直接进入dead 状态。

  public class NewThread implements Runnable 

    @Override
    public synchronized void run() 
        while (true) 
            System.out.println("线程运行了...");
            try 
//                Thread.sleep(100);
                wait();
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    

    public static void main(String[] args) 
        //创建线程并执行线程任务
        NewThread target = new NewThread();
        Thread thread = new Thread(target);
        //线程启动
        thread.start();

        while (true) 
            synchronized (target) 
                System.out.println("主线程");
                try 
                    Thread.sleep(100);
                 catch (InterruptedException e) 
                    e.printStackTrace();
                
                target.notify();
            
        
    

创建线程的多种方式

继承Thread类

创建线程:

public class Demo1 extends Thread 

    public Demo1(String name) 
        super(name);
    


    @Override
    public void run() 
        while (true) 
            System.out.println(getName() + "线程执行...");
        
    

    public static void main(String[] args) 
        Demo1 d1 = new Demo1("first-thread");
        Demo1 d2 = new Demo1("second-thread");

        //(守护线程) 即使线程没有执行完毕,只要主线程执行完了,线程就会退出
        d1.setDaemon(true);
        d2.setDaemon(true);
        d1.start();
        d2.start();
        try 
            Thread.sleep(2000);
         catch (InterruptedException e) 
            e.printStackTrace();
        

    

线程的中断:

使用stop()方式没有释放锁和资源,只是让线程无限期的等待下去
推荐使用interrupt()

public class Demo1 extends Thread 

    public Demo1(String name) 
        super(name);
    

    @Override
    public void run() 
        while (!interrupted()) 
            System.out.println(getName() + "线程执行...");
            try 
                Thread.sleep(200);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    
    public static void main(String[] args) 
        Demo1 d1 = new Demo1("first-thread");
        Demo1 d2 = new Demo1("second-thread");

        d1.start();
        d2.start();
        d1.interrupt();

    

实现Runnable接口

/**
 * 作为线程任务存在
 */
public class Demo2 implements Runnable 

    @Override
    public void run() 
        while (true) 
            System.out.println("thread running");
        
    
   
    public static void main(String[] args) 
        Thread thread = new Thread(new Demo2());
        thread.start();
    

匿名内部类的方式

public class Demo3 
    public static void main(String[] args) 
        //该线程仅创建一次
        new Thread() 
            @Override
            public void run() 
                while (true) 
                    System.out.println("thread start...");
                
            
        .start();

        new Thread(new Runnable() 
            @Override
            public void run() 
                System.out.println("thread start...");
            
        ).start();

        //执行结果为sub
        new Thread(new Runnable() 
            @Override
            public void run() 
                System.out.println("runnable");
            
        ) 
            @Override
            public void run() 
                System.out.println("sub");
            
        .start();
    

带返回值的线程

public class Demo4 implements Callable<Integer> 
    public static void main(String[] args) throws ExecutionException, InterruptedException 
        //执行的任务
        Demo4 d = new Demo4();
        FutureTask<Integer> task = new FutureTask<Integer>(d);
        Thread t = new Thread(task);
        t.start();
        System.out.println("我先干点别的");
        //拿回返回结果
        Integer integer = task.get();
        System.out.println("线程执行的结果为:" + integer);
    

    @Override
    public Integer call() throws Exception 
        System.out.println("正在进行紧张的计算");
        Thread.sleep(3000);

        return 1;
    

定时器

public class Demo5 

    public static void main(String[] args) 
        Timer timer = new Timer();
        timer.schedule(new TimerTask() 
            @Override
            public void run() 
                //实现定时任务
                System.out.println("timertask is run");
            
        , 0, 1000);
    

线程池的实现

newFixedThreadPool:

public class Demo6 

    public static void main(String[] args) 
        ExecutorService threadPool = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 100; i++) 
            threadPool.execute(new Runnable() 
                @Override
                public void run() 
                    System.out.println(Thread.currentThread().getName());
                
            );
        
        threadPool.shutdown();
    

newCachedThreadPool:

public class Demo6 
    public static void main(String[] args) 

        //比较智能的线程池,不够用就创建,够用就回收
        ExecutorService threadPool = Executors.newCachedThreadPool();

        for (int i = 0; i < 100; i++) 
            threadPool.execute(new Runnable() 
                @Override
                public void run() 
                    System.out.println(Thread.currentThread().getName());
                
            );
        

        threadPool.shutdown();
    

Lambda表达式实现

public class Demo7 

    public int add(List<Integer> values) 
//        values.stream().forEach(System.out::println);
        return values.parallelStream().mapToInt(a -> a).sum();
    

    public static void main(String[] args) 
        List<Integer> values = Arrays.asList(10, 20, 30, 40);
        int result = new Demo7().add(values);
        System.out.println(result);
    

Spring 实现多线程

Main方法:

public class Application 

    public static void main(String[] args) 
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
        DemoService bean = ac.getBean(DemoService.class);
        bean.a();
        bean.b();
    

相关配置

@Configuration
@ComponentScan("com.autohome.data.realtime.demo")
@EnableAsync
public class Config 

异步代码:
?

@Service
public class DemoService 

    @Async
    public void a() 
        while (true) 
            System.out.println("a");
            try 
                Thread.sleep(100);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        

    
    @Async
    public void b() 
        while (true) 
            System.out.println("b");
            try 
                Thread.sleep(100);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    

以上是关于如何创建多线程的主要内容,如果未能解决你的问题,请参考以下文章

多个用户访问同一段代码

线程学习知识点总结

Java多线程概述及创建

newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段

八.多进程与多线程

线程同步-使用ReaderWriterLockSlim类