7. 获取多线程的三种方式

1. 继承Thread类

重写Thread的run()方法,把线程运行逻辑放在其中

package com.threadtest;
class MyThread extends Thread{
    
    private int ticket = 10;
    private String name;
    public MyThread(String name){
        this.name =name;
    }
    
    public void run(){
        for(int i =0;i<500;i++){
            if(this.ticket>0){
                System.out.println(this.name+"卖票---->"+(this.ticket--));
            }
        }
    }
}
public class ThreadDemo {

    
    public static void main(String[] args) {
        MyThread mt1= new MyThread("一号窗口");
        MyThread mt2= new MyThread("二号窗口");
        MyThread mt3= new MyThread("三号窗口");
        mt1.start();
        mt2.start();
        mt3.start();
    }

}

2. 实现Ruunable接口

package com.threadtest;
class MyThread1 implements Runnable{
    private int ticket =10;
    private String name;
    public void run(){
        for(int i =0;i<500;i++){
            if(this.ticket>0){
                System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
            }
        }
    }
}
public class RunnableDemo {

    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //设计三个线程
         MyThread1 mt = new MyThread1();
         Thread t1 = new Thread(mt,"一号窗口");
         Thread t2 = new Thread(mt,"二号窗口");
         Thread t3 = new Thread(mt,"三号窗口");
//         MyThread1 mt2 = new MyThread1();
//         MyThread1 mt3 = new MyThread1();
         t1.start();
         t2.start();
         t3.start();
    }

}

3. 实现Callable接口

class MyThread implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println("******come here");
        //暂停一会儿线程
        try{

            TimeUnit.SECONDS.sleep(4);
        }catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return 1024;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask futureTask = new FutureTask(new MyThread());
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();
        System.out.println(Thread.currentThread().getName()+"main****计算完成");
        System.out.println(futureTask.get());
    }
}

需要用FutureTask关联runnable接口和callable接口。
Callable接口的好处是不会让住线程阻塞等待,而是会继续主线程。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容