• 线程实现的三种方式


    线程实现的三种方式

    方式一,继承Thread类:

    package com.yonyou.sci.gateway;
    
    /**
     * Created by Administrator on 2019/8/15.
     */
    public class SubThread extends Thread{
    
        // 更改线程名字方法一
    //    public SubThread () {
    //        super("Thread 1");
    //    }
    
        @Override
        public void run () {
            // 更改线程名字方法二
    //        setName("Thread 2"); 
    
            for (int i = 0;i < 3; i++) {
                System.out.println(getName()+"_"+i);
            }
        }
    
        public static void main(String[] args) {
            SubThread st = new SubThread();
            st.start();
        }
    
    }

    方式二,实现Runnable接口:

    package com.yonyou.sci.gateway;
    
    /**
     * Created by Administrator on 2019/8/16.
     */
    public class SubRunnable implements Runnable{
    
        @Override
        public void run () {
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName()+"_"+i);
            }
        }
    
        public static void main(String[] args) {
            SubRunnable sr = new SubRunnable();
            Thread t = new Thread(sr);
            // 更改线程名字
            t.setName("123");
            
            t.start();
        }
    
    }

    方式三、实现Callable<String>接口:

    备注:a.此接口特点是有返回值; b.能抛出异常。

    package com.yonyou.sci.gateway;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.FutureTask;
    
    public class SubCallable implements Callable<String> {
    
        @Override
        public String call () {
            return "call";
        }
    
        public static void main(String[] args) throws Exception{
            SubCallable sc = new SubCallable();
            FutureTask<String> ft = new FutureTask<String>(sc);
            Thread t = new Thread(ft);
            t.start();
            String s = ft.get();
            System.out.println(s);
        }
    
    }
  • 相关阅读:
    jQuery1.3.2 源码学习 2 两个重要的正则表达式
    学习 jQuery 4 使用方法选择
    学习 jQuery 6 在 TreeView 中实现全选
    jQuery1.3.2 源码学习4 init 函数分析 2
    学习 jQuery 3 选择器
    学习 jQuery 5 筛选和过滤器
    条款9:在删除选项中仔细选择
    优化3D图形流水线
    指针相减
    浅谈水体的实现
  • 原文地址:https://www.cnblogs.com/tangshengwei/p/11723471.html
Copyright © 2020-2023  润新知