java基础线程-继承Runnable接口

来源:互联网 发布:c语言函数编程心得体会 编辑:程序博客网 时间:2024/05/19 22:02
package common;/** * Created by shao on 2016/11/3. */public class ThreadTest implements Runnable{    @Override    public void run() {        System.out.println(Thread.currentThread().getName() + " 我已开始运行了" );        synchronized(this){            for (int i = 0; i < 5; i++) {                try {                    Thread.sleep(1000);                    System.out.println(Thread.currentThread().getName() + " " +i);                } catch (Throwable e) {                    System.out.println(e);                }            }        }        System.out.println(Thread.currentThread().getName() + " 我运行结束了" );    }    public static void main(String args[]) {        int number = 0;        ThreadTest tt=new ThreadTest();        try {            Thread th1 = new Thread(tt);            th1.setName("邵飞飞是高手");            th1.start();            Thread th2 = new Thread(tt);            th2.setName("高手");            th2.start();        } catch (Throwable e) {            System.out.println(e);        }    }}


Java线程实现方法有很多种,这里先介绍使用Runnable接口,Runnable接口有一个抽象方法Run(),需要重写。synchronized用来修饰一个方法或者一个代码块,它用来保证在同一时刻最多只有一个线程执行该段代码。synchronized可以修饰代码段。也可以修饰方法。Thread.currentThread()是获得当前Run方法中的线程对象。


0 0