首页 > 代码库 > java 创建线程
java 创建线程
java创建线程有3种方式:
(1)继承Thread
(2)实现Runnable接口
(3)实现Callable接口
1、继承Thead
- package com.java.thread;
- public class ThreadClient {
- public static void main(String[] args) {
- Print p1 = new Print();
- Print p2 = new Print();
- p1.start();
- p2.start();
- }
- }
- class Print extends Thread{
- @Override
- public void run(){
- for(int i=0;i<10;i++){
- System.out.println(Thread.currentThread().getName()+":"+i);
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
2、实现Runnable接口
- package com.java.thread;
- public class ThreadClient1 {
- public static void main(String[] args) {
- Runnable p1 = new Salesman("Jack");
- Runnable p2 = new Salesman("Iris");
- Thread t1 = new Thread(p1);
- Thread t2 = new Thread(p2);
- t1.start();
- t2.start();
- }
- }
- class Salesman implements Runnable{
- private int ticket=100;
- private String name;
- Salesman(String name){
- this.name=name;
- }
- @Override
- public void run(){
- while(ticket>0){
- System.out.println(ticket--+" is saled by "+name+","+Thread.currentThread().getName());
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
3、实现Callable接口
- package com.java.thread;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class CallType {
- public static void main(String[] args) {
- ExecutorService es = Executors.newCachedThreadPool();
- List<Future<String>> results = new ArrayList<Future<String>>();
- for(int i=0;i<5;i++){
- results.add(es.submit(new TaskWithResult(i)));
- }
- for(Future<String> fs : results){
- try {
- System.out.println(fs.get());
- } catch (InterruptedException | ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- class TaskWithResult implements Callable<String>{
- private int id;
- public TaskWithResult(int id){
- this.id = id;
- }
- @Override
- public String call() throws Exception {
- return "result of TaskWithResult" + id;
- }
- }
由于Java只支持单继承,所以用继承的方式创建线程,比较死板,不够灵活;用实现接口的方式创建线程,可以实现多个接口,比较灵活。
Runnable和Callable接口的区别:
(1)Callable重写的方法是call(),Runnable重写的方法是run()。
(2)Callable的任务执行后可返回值,而Runnable不能返回值。
(3)call方法可以抛出异常,run()不可以。
java 创建线程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。