线程

实现runable

public class DisplayMessage implements Runnable {
    public String message;

    public DisplayMessage(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(message + Thread.currentThread().getName());
        }
    }
    public static void main(String[] args) {
        Runnable hello = new DisplayMessage("Hello");
        Thread thread1 = new Thread(hello);
        thread1.setDaemon(true);
        thread1.setName("hello");
        System.out.println("starting hello basic.thread");
        thread1.start();
    }
}

继承Thread

public class GuessANumber extends Thread {
    public int number;

    public GuessANumber(int number) {
        this.number = number;
    }

    @Override
    public void run() {
        int guess = 0;
        int counter = 0;
        do {
            guess = (int) (Math.random() * 1000 +1);
            System.out.println(this.getName() + "guess" + guess);
            counter ++;
        } while (guess != number);
        System.out.println();
    }
    public static void main(String[] args) {
        Thread thread4 = new GuessANumber(70);
        thread4.start();
    }
}

实现Callable


public class CallableThreadTest implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 10; i++) {
            System.out.println("" + i);
        }
        return i;
    }

    public static void main(String[] args) {
        CallableThreadTest threadTest = new CallableThreadTest();
        FutureTask ft = new FutureTask(threadTest);
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName());
            new Thread(ft, "有返回值的线程").start();
        }
        try {
            System.out.println("返回值:" + ft.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值