创建多线程方法

/**
 * run()相当于线程的任务处理逻辑的入口方法
 * start()的作用是启动相应的线程
 * @author yiRain
 *
 */
public class startAndRun {
    public static void  main(String[] args) {
        Thread t = new Thread(){
            public void run(){
                world();
            }
        };
        
        t.start();
        //t.run();
        System.out.print(" Hello ");
    }
    
    static void world(){
        System.out.print(" world ");
    }

}

1.start()方法来启动线程,真正实现了多线程运行。这时无需等待run方法体代码执行完毕,可以直接继续执行下面的代码;通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体,它包含了要执行的这个线程的内容, Run方法运行结束, 此线程终止。然后CPU再调度其它线程。
2.run()方法当作普通方法的方式调用。程序还是要顺序执行,要等待run方法体执行完毕后,才可继续执行下面的代码; 程序中只有主线程——这一个线程, 其程序执行路径还是只有一条, 这样就没有达到写线程的目的。
记住:多线程就是分时利用CPU,宏观上让所有线程一起执行 ,也叫并发
————————————————

因此t.start()结果为hello world
t.run()结果为world hello(调用后立即执行)

一个线程调用 两次start()方法将会抛出线程状态异常,也就是的start()只可以被调用一次

1.继承Thread

new Thread().start;

2.实现Runnable

new Thread(new Runnable()).start;

3.实现Callable

FutureTask task=new FutureTask(new Callable01());
new Thread(task).start();
System.out.println(task.get());

代码:

public class Thread01 extends Thread {

    @Override
    public void run(){

        System.out.println("000000000000");
    }
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread01();
        thread.start();
        //thread.run();
        //Thread.sleep(1);
        System.out.println("11111111111");
    }

}
public class Runnable01 implements Runnable{
    @Override
    public void run() {
        System.out.println("线程启动");
    }

    public static void main(String[] args) {
        new Thread(new Runnable01()).start();
    }
}

public class Callable01 implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "线程启动";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask task=new FutureTask(new Callable01());
        new Thread(task).start();
        System.out.println(task.get());
        //区别是main可以拿到线程的结果

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值