Java 多线程

        Java多线程的实现这里介绍三个

  1. 继承Thread,重写run方法
  2. 实现Runnable接口,重写run方法,将对象装配进Thread对象
  3. 实现Callable接口,重写call方法,可以带返回值,将对象装配进FutureTask中,再将FutureTask对象装配进Thread中

Thread

 MyThread类

package com.igeek.learn;

public class MyThread extends Thread{
    int num = 100;

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(getName()+":"+ --num);
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

TestThread 

package com.igeek.learn;

public class TestThread {
    public static void main(String[] args) {
        MyThread th = new MyThread();
        MyThread th1 = new MyThread();
        th.start();
        th1.start();
    }
}

Runnable

MyRunnable类

package com.igeek.learn;

public class MyRunnable implements Runnable{

    int num = 100;

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+":"+num--);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

TestRunnable

package com.igeek.learn;

public class TestRunnable {
    public static void main(String[] args) {
        MyRunnable my = new MyRunnable();
        Thread thread = new Thread(my,"线程1");
        thread.start();

        Thread thread1 = new Thread(my,"线程2");
        thread1.start();
    }
}

        特别注明,由于这里线程并没有上锁,所以会脏数据,导致每次运行结果都有可能不同,如何上锁我们放在下一次去说明。

Callable

MyCallable

package com.igeek.learn;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+":"+ i);
            Thread.sleep(1000);
        }
        return "I Love Java";
    }
}

TestCallable

package com.igeek.learn;

import java.util.concurrent.FutureTask;

public class TestCallable {
    public static void main(String[] args) throws Exception{
        MyCallable myCallable = new MyCallable();
        FutureTask<String> fu = new FutureTask<>(myCallable);
        Thread th = new Thread(fu,"线程1");
        th.start();

        FutureTask<String> fu1 = new FutureTask<>(myCallable);
        Thread th1 = new Thread(fu1,"线程2");
        th1.start();

        System.out.println(fu.get());
        System.out.println(fu1.get());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值