多线程——范例:建立与启动两个线程 与 范例:显示调度器有多个不可预测的结果(Head First Java的例子)

Posted CYTing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程——范例:建立与启动两个线程 与 范例:显示调度器有多个不可预测的结果(Head First Java的例子)相关的知识,希望对你有一定的参考价值。

//范例:建立与启动两个线程
public class ThreadTest implements Runnable{
    public static void main(String[] args) {
        ThreadTest runner=new ThreadTest();//创建Runnable的实例
        Thread alpha=new Thread(runner);
        Thread beta=new Thread(runner);//创建两个线程,使用相同的Runnable,即相同的任务
        alpha.setName("Alpha thread");
        beta.setName("Beta thread");//给线程取名字
        alpha.start();
        beta.start();//启动线程
    }

    @Override
    public void run() {
        for(int i=0;i<25;i++){
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+" "+i+" is running");
        }
    }
    
}

输出结果:

Beta thread 0 is running
Beta thread 1 is running
Alpha thread 0 is running
Alpha thread 1 is running
Alpha thread 2 is running
Alpha thread 3 is running
Alpha thread 4 is running
Alpha thread 5 is running
Alpha thread 6 is running
Alpha thread 7 is running
Alpha thread 8 is running
Alpha thread 9 is running
Alpha thread 10 is running
Alpha thread 11 is running
Alpha thread 12 is running
Alpha thread 13 is running
Alpha thread 14 is running
Alpha thread 15 is running
Alpha thread 16 is running
Alpha thread 17 is running
Alpha thread 18 is running
Alpha thread 19 is running
Alpha thread 20 is running
Alpha thread 21 is running
Alpha thread 22 is running
Alpha thread 23 is running
Alpha thread 24 is running
Beta thread 2 is running
Beta thread 3 is running
Beta thread 4 is running
Beta thread 5 is running
Beta thread 6 is running
Beta thread 7 is running
Beta thread 8 is running
Beta thread 9 is running
Beta thread 10 is running
Beta thread 11 is running
Beta thread 12 is running
Beta thread 13 is running
Beta thread 14 is running
Beta thread 15 is running
Beta thread 16 is running
Beta thread 17 is running
Beta thread 18 is running
Beta thread 19 is running
Beta thread 20 is running
Beta thread 21 is running
Beta thread 22 is running
Beta thread 23 is running
Beta thread 24 is running

 

//范例:显示调度器有多个不可预测的结果
class MyRunnable implements Runnable{
    
    @Override
    public void run() {
        go();
    }
    public void go(){
        doMore();
    }
    public void doMore(){
        System.out.println("top o‘ the stack");
    }
}

public class ThreadTest2{
public static void main(String[] args) {
        Runnable threadJob=new MyRunnable();
        Thread myThread=new Thread(threadJob);
        myThread.start();
        System.out.println("back in main");
    }
}

输出结果:

back in main
top o‘ the stack

top o‘ the stack

back in main

以上是关于多线程——范例:建立与启动两个线程 与 范例:显示调度器有多个不可预测的结果(Head First Java的例子)的主要内容,如果未能解决你的问题,请参考以下文章

Java Socket编程 标准范例(多线程)

python多线程模块thread使用范例的代码

C++11多线程 原子操作概念及范例

jmeter测试范例001——TCP测试

Java 死锁范例以及如何分析死锁

java_第9章:多线程