Java多线程编程

Java多线程的写法有几种,这里列举其中的两种


1. 通过继承Thread 类定义新线程

public class SubclassThread extends Thread {  
    public void run() {  
        while (true) {  
        // 执行线程自身的任务  
            try {  
                sleep(5 * 1000);  
                break;  
            } catch (InterruptedException exc) {  
            // 睡眠被中断  
            }  
        }  
    }  
    public static void main(String[] args) {  
        Thread thread = new SubclassThread();  
        thread.start();  
        System.out.println("主程序结束");  
    }  
}


2. 通过实现Runnable 接口定义新线程
class Counter implements Runnable {  
    public void run() {  
        for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);  
    }  
}  
public class RunnableThread {  
    public static void main(String[] args) {  
        Counter counter = new Counter();  
        Thread thread = new Thread(counter);  
        thread.start();  
        System.out.println("主程序结束");  
    }  
}


在利用Runnable接口定义线程的学习中,笔者还学习了使用线程池的方式来启动线程

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
  
class Counter implements Runnable {  
    public void run() {  
        for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);  
    }  
}  
  
public class Runner {  
  
    public static void main(String[] args) {  
        ExecutorService application = Executors.newCachedThreadPool(); //申请一个线程池  
          
        application.execute(new Counter()); // 从线程池中运行一个新线程  
          
        application.shutdown(); // 关闭线程池  
    }  
  
}


优缺点:

Runnable:

优点:节约java宝贵的单继承指标。

缺点:运行时需要构建一个Thread实例来运行或者创建线程池服务来运行实现的Runnable。

Thread:

优点:实现的时候代码较为简单。

缺点:实现需要继承Thread。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值