zoukankan      html  css  js  c++  java
  • 线程实现的三种方式

    线程实现的三种方式

    方式一,继承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);
        }
    
    }
  • 相关阅读:
    使用VS2015将解决方案同步更新到Github上
    SQL Server循环
    OSPF
    OPSF
    OSPF
    pandas更换index,column名称
    pandas的时间戳
    pandas选择单元格,选择行列
    BGP
    BGP
  • 原文地址:https://www.cnblogs.com/tangshengwei/p/11723471.html
Copyright © 2011-2022 走看看