How to create multiple threads

State of the thread

Initialization - Ready - run - termination

Sleep: Timeout waiting, over a period of time it will enter the ready state to compete cpu resources.

Wait: wait state, no, we will have to wait through notify or notifyAll wake.

Block: When block io or face lock code, or receive data to obtain the lock will be operational state, it is also possible directly into the dead state.

  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();
            }
        }
    }
}

A variety of ways to create a thread

Thread class inheritance

Create a 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();
        }

    }
}

Thread interrupts:

Use stop () there is no way to release the lock and resource, just let down a thread to wait indefinitely
recommended 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();

    }
}

Implement 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();
    }
}

Anonymous inner class way

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();
    }
}

Thread with a return value

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;
    }
}

Timer

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);
    }
}

Achieve thread pool

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 expressions realization

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 multi-threaded

Main method:

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();
    }

}

Related

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

}

Asynchronous code:

@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();
            }
        }
    }
}

Guess you like

Origin www.cnblogs.com/bigdata1024/p/10991099.html