1.继承Runnable接口

package com.vince.xq.kafka.thread;

public class ThreadOne implements Runnable {

    private int i;
    public ThreadOne(int i) {
        this.i=i;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(i);
    }

}

使用

package com.vince.xq.kafka;

import com.vince.xq.kafka.thread.ThreadOne;

public class TestThread {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new ThreadOne(i));
            thread.start();
        }
    }

}

结果

2.继承Thread 类

package com.vince.xq.kafka.thread;

public class ThreadTwo extends Thread {
    private int i;
    public ThreadTwo(int i){
        this.i=i;
    }

    @Override
    public void run() {
        System.out.println(i);
    }
}

 使用

package com.vince.xq.kafka;

import com.vince.xq.kafka.thread.ThreadTwo;

public class TestThread {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Thread thread = new ThreadTwo(i);
            thread.start();
        }
    }

}

结果

3.继承callable接口

package com.vince.xq.kafka.thread;

import java.util.concurrent.Callable;

public class ThreadThree implements Callable<String> {
    @Override
    public String call() {
        try {
            int x = 10 / 1;
            return "test";
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }

    }
}

使用

package com.vince.xq.kafka;

import com.vince.xq.kafka.thread.ThreadThree;

import java.util.concurrent.*;

public class TestThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        FutureTask<String> futureTask = new FutureTask<>(new ThreadThree());
        threadPoolExecutor.submit(futureTask);
        System.out.println(futureTask.get());//主线程等子线程结束
        threadPoolExecutor.shutdown();
    }

}

4.主线程等子线程结束实现方法

(1)Future.get()

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        FutureTask<String> futureTask = new FutureTask<>(new ThreadThree());
        threadPoolExecutor.submit(futureTask);
        System.out.println(futureTask.get());//主线程等子线程结束
        threadPoolExecutor.shutdown();

(2)CountDownLatch

package com.vince.xq.kafka;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class TestThread {

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(2);

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(()-> {
            try {
                test1(countDownLatch);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.execute(()-> {
            try {
                test2(countDownLatch);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.shutdown();
        countDownLatch.await();
        System.out.println("0000");
        System.out.println("costTime:");
        System.out.println(System.currentTimeMillis() - startTime);

    }

    public static void test1(CountDownLatch countDownLatch) throws InterruptedException {
        Thread.sleep(2000);
        System.out.println(111);
        countDownLatch.countDown();
        //return "111";
    }

    public static void test2(CountDownLatch countDownLatch) throws InterruptedException {
        Thread.sleep(2000);
        System.out.println(222);
        countDownLatch.countDown();
    }

    public static String test3() throws InterruptedException {
        Thread.sleep(2000);
        return "333";
    }

}

class MyUncaughtExceptionHandle implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("caught " + e);
    }
}


class HandleThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        System.out.println("create thread t");
        Thread t = new Thread(r);
        System.out.println("set uncaughtException for t");
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandle());
        return t;
    }


}

(3)Thread.join()

long startTime = System.currentTimeMillis();
Thread thread = new Thread(new ThreadOne("1"));
thread.start();
//thread.join();
long costTime = System.currentTimeMillis() - startTime;
System.out.println("costTime:" + costTime);



package com.vince.xq.kafka.thread;

import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadOne implements Runnable {

    private static AtomicBoolean exists = new AtomicBoolean(false);
    private String name;

    public ThreadOne(String i) {
        this.name = i;
    }

    @Override
    public void run() {
        if (exists.compareAndSet(false, true)) {
            System.out.println(name + "start");
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            exists.set(false);
            System.out.println("111111");
        } else {
            System.out.println(name + " give up");
        }
    }

}

没有thread.join

 有thread.join

5.java 守护线程

java并发编程学习: 守护线程(Daemon Thread) - 菩提树下的杨过 - 博客园 (cnblogs.com)

一个线程去执行数据,一个线程设置为守护线程去打印日志

Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐