• Java多线程-----匿名内部类创建线程


       1.继承Thread类创建线程

    package com.practise.createthread;
    
    public class AnonymousThread {
        public static void main(String[] args) {
            new Thread("线程一") {
                public void run() {
                    for(int i=1;i<=20;i++) {
                        System.out.println(Thread.currentThread().getName()+":"+i);
                    }
                }
            }.start();
            
            Thread.currentThread().setName("主线程");
            for(int i=1;i<=20;i++) {
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }

       2.实现Runnable接口创建线程

    package com.practise.createthread;
    
    public class AnonymousThread {
        public static void main(String[] args) {        
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    for(int i=1;i<=20;i++) {
                        System.out.println(Thread.currentThread().getName()+":"+i);
                    }            
                }
            }, "线程二").start();
            
            Thread.currentThread().setName("主线程");
            for(int i=1;i<=20;i++) {
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }

       3.使用Callable和Future创建线程

    package com.practise.createthread;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.FutureTask;
    
    public class AnonymousThread {
        public static void main(String[] args) {
            FutureTask<Integer> task=new FutureTask<Integer>(new Callable<Integer>() {
                @Override
                public Integer call() {
                    Integer total = 0;
                    try {
                        for (int i = 1; i <= 50; i++) {
                            total += i;
                        }
                        return total;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    return null;
                }
            });
            
            new Thread(task, "有返回值的线程").start();
            try {
                System.out.println(task.get());
            } catch (Exception ex) {
                ex.printStackTrace();
            } 
    
            Thread.currentThread().setName("主线程");
            for (int i = 1; i <= 20; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
  • 相关阅读:
    hdu1754线段树入门
    hdu1247 字典树模板
    完全背包 poj 1384
    hdu 1541 树状数入门
    hdu 2665 划分树模板
    winhex分析磁盘目录结构(未完待续)
    取出表单中元素的js代码
    c语言检测cpu大小端模式
    firefox的cookie
    c移位实现求余
  • 原文地址:https://www.cnblogs.com/fengfuwanliu/p/10131481.html
Copyright © 2020-2023  润新知