java 多线程基础

Posted 诸葛子房_

tags:

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

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

}

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

java基础入门-多线程同步浅析-以银行转账为样例

java多线程基础

Java基础之多线程

Java多线程基础

多线程编程学习一(Java多线程的基础)

Java 多线程基础多线程的实现方式