Java线程理解(1)

来源:互联网 发布:ubuntu出错 编辑:程序博客网 时间:2024/05/22 03:21

1.线程Thread

单线程:在启动程序中只有一个main()程序进入点开始至结束。多线程:有多个线程并行运行。

值得注意的是:

1.1. 线程看起来像是同时执行,但是事实上同一时间点,一个CPU还是只能执行一个线程,只是CPU会不断的切换线程,且切换的很快,所以看起来像是同时进行。
1.2 线程有优先权,可使用Thread的setPriority()方法设定优先权,可设定值从1到10,超过则会抛出异常IllegalArgumentException。数字越大优先级越高。如果优先权相同,则输流执行。

2.Runnable的run()方法
在Java 中,任何线程可执行的流程都要定义在Runnable的run()方法,这样做得好处是:操作Runnable 接口具有较好的弹性,使用的类还可以继承其他类。
下面是龟兔赛跑的例子,龟和兔使用Runnable接口,分别重新定义自己的run方法。后面建立两个线程,分别填充龟和兔的对象,使二者在不同的进程中运行,从而实现二者run动作同时执行。其中乌龟1s跑1步,兔子睡觉随机,醒来1s跑2步。
实例:
龟:Tortoise.java

public class Tortoise implements Runnable{    private int totalStep;    private int step;    public Tortoise(int totalStep){        this.totalStep =totalStep;    }    @Override    public void run(){        try{            while(step<totalStep){                Thread.sleep(1000);                step++;                System.out.printf("乌龟跑了 %d步...%n",step);            }        }catch(InterruptedException ex) {            throw new RuntimeException(ex);        }    }}

兔子:Hare.java

public class Hare implements Runnable{    private boolean[] flags={true,false};    private int totalStep;    private int step;    public Hare(int totalStep){        this.totalStep =totalStep;    }    @Override    public void run(){        try{            while(step<totalStep){                Thread.sleep(1000);                boolean isHareSleep=flags[((int)(Math.random()*10))%2];//random产生0.0~1.0的数据,*10得0~10用2取余得0或1                if(isHareSleep){//只有两种结果true or false                    System.out.println("兔子睡着了zzzz");                }else{                        step +=2;                        System.out.printf("兔子跑了 %d步...%n",step);                }            }        }catch(InterruptedException ex) {            throw new RuntimeException(ex);        }    }}

主程序: TortoiseHareRace.java

public class TortoiseHareRace{    public static void main(String [] args){        Tortoise tortoise =new Tortoise(10);        Hare hare=new Hare(10);        Thread tortoiseThread =new Thread(tortoise);        Thread hareThread =new Thread(hare);        hareThread.start();        tortoiseThread.start();    }}       

运行结果:
这里写图片描述

> 需要注意的是,定义的类也可以直接继承Thread重新定义run()方法,这是因为Thread类本身也操作了Runnable接口。

0 0
原创粉丝点击