Java基础之线程

来源:互联网 发布:淘宝开食品店没证件 编辑:程序博客网 时间:2024/05/23 01:17

1 线程

1.1 概念

同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器(PC),线程切换开销小。

1.2 创建线程

第一种:直接建立一个Thread子线程,并启动

   new Thread() {        @Override        public void run() {             //这里写入子线程需要做的工作        }   }.start();   // 完毕
public class ThreadDemo1 {     public static void main(String[] args){         MyThread thread = new MyThread();         thread.start();         for(int i=0;i<60;i++){             System.out.println(Thread.currentThread().getName()+i);         }     } } class MyThread extends Thread{     public void run(){         for(int i=0;i<60;i++){             System.out.println(Thread.currentThread().getName()+i);         }     } }

第二种:建立一个Thread子线程,实现Runnable接口,然后启动。

  //声明一个子线程  private Thread newThread;   newThread = new Thread(new Runnable() {    @Override            public void run() {            //这里写入子线程需要做的工作            }        });    newThread.start(); //启动线程
public class ThreadDemo2 {    public static void main(String[] args){        MyRunnable runnable =new MyRunnable();        Thread thread = new Thread(runnable);        thread.start();        for(int x=0;x<60;x++){            System.out.println(Thread.currentThread().getName()+x);        }    }}class MyRunnable implements Runnable{    public void run(){        for(int x=0;x<60;x++){            System.out.println(Thread.currentThread().getName()+x);        }    }}

1.3 线程的生命周期

线程同样要经历“开始(等待)、运行、阻塞和停止”四种不同的状态。这四种状态都可以通过Thread类中的方法进行控制。

// 开始publicvoid start( );// 运行publicvoid run( );// 阻塞// 停止线程publicvoid stop( );      

1.4 常用方法

// 取得线程名称getName();// 取得当前线程对象curentThread()// 挂起和唤醒线程public void resume( );    // 得到线程状态,是否启动publicboolean isAlive( );// 线程睡眠,(Thread.sleep(1000))public static void sleep(long millis);public static void sleep(long millis, int nanos);// 线程强行加入publicvoid join( ) throws InterruptedException;
0 0
原创粉丝点击