Java并发编程-1 基本线程机制

1 线程构造方法

方法1:通过Runnable接口描述线程任务

  • 实现Runnable接口中的run方法
public class RunnableThread implements Runnable {
    public void run()
    {                   //Thread.MIN_PRIORITY,Thread.NORM_PRIORITY,Thread.MAX_PRIORITY//Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        Long thread_id = Thread.currentThread().getId();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.print("this is RunnableThread, thread id = " + thread_id.toString() + '\n');
    }
}
    Long thread_id = Thread.currentThread().getId();
  • 通过Thread类启动RunnableThread线程
public class MyThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        RunnableThread runnableThread = new RunnableThread();
        Thread thread = new Thread(runnableThread);
        thread.start();
        System.out.print("main thread id is = " + Thread.currentThread().getId() + '\n');
        thread.join();
    }
}
  • 通过Executor执行器创建线程
public class MyThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        RunnableThread runnableThread = new RunnableThread();
        ExecutorService exec_run = Executors.newCachedThreadPool();
        for(int i = 0; i < 5; i++)
        {
            exec_run.execute(new RunnableThread());
        }
        exec_run.shutdown();
    }
}

方法2:通过Callable接口创建可返回参数的任务

  • 实现接口Callable中的call方法
import java.util.concurrent.*;
import java.util.*;
public class CallableThread implements Callable<String> {
    private int id;
    public  CallableThread(int id)
    {
        this.id = id;
    }
    public String call() throws InterruptedException {

        long thread_id = Thread.currentThread().getId();
        Thread.sleep(200);
        return "result of RunnableThread " + id + " thread id = " + thread_id;
    }
}
  • 通过Executor执行器执行
public class MyThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService exec_call = Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures = new ArrayList<Future<String>>();
        for(int i = 0; i < 10; i++)
            futures.add(exec_call.submit(new CallableThread(i)));
        for(Future<String> fs : futures)
            System.out.print(fs.get() + '\n');
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值