Java 多线程之一(Thread Or Runable)

来源:互联网 发布:淘宝房源 编辑:程序博客网 时间:2024/05/19 12:38

线程分为守护线程Daemon Thread(典型应用是垃圾回收器),非守护线程User Thread


加入同步方法之后:


加入线程通信之后:


1. Runable接口

@FunctionalInterfacepublic interface Runnable {    /**     * When an object implementing interface <code>Runnable</code> is used     * to create a thread, starting the thread causes the object's     * <code>run</code> method to be called in that separately executing     * thread.     * <p>     * The general contract of the method <code>run</code> is that it may     * take any action whatsoever.     *     * @see     java.lang.Thread#run()     */    public abstract void run();}

2. Callable接口

@FunctionalInterfacepublic interface Callable<V> {    /**     * Computes a result, or throws an exception if unable to do so.     *     * @return computed result     * @throws Exception if unable to compute a result     */    V call() throws Exception;}


3. Thread类

public class Thread implements Runnable {}

4. run()和start()区别

public class mutilThread extends Thread{String name;public mutilThread(String name){this.name=name;}public void run(){for(int i=1;i<10;i++){System.out.println("线程:"+this.name+" "+i);}}public static void main(String[] args) {// TODO Auto-generated method stubmutilThread m1=new mutilThread("a");mutilThread m2=new mutilThread("b");m1.start();m2.start();}}

start()的输出:

线程:a 1
线程:a 2
线程:a 3
线程:b 1
线程:b 2
线程:b 3
线程:b 4
线程:a 4
线程:a 5
线程:b 5
线程:b 6
线程:b 7
线程:b 8
线程:b 9
线程:a 6
线程:a 7
线程:a 8
线程:a 9
run()的输出:

线程:a 1
线程:a 2
线程:a 3
线程:a 4
线程:a 5
线程:a 6
线程:a 7
线程:a 8
线程:a 9
线程:b 1
线程:b 2
线程:b 3
线程:b 4
线程:b 5
线程:b 6
线程:b 7
线程:b 8
线程:b 9

在Java中,线程通常有五种状态:

第一是创建态:即创建新的线程对象,并没有隐式调用start()方法;

第二是就绪态:当调用了线程对象的start方法之后,该线程就进入了就绪态,但此时线程调度程序还没有把该线程设置为当前态;

第三是运行态:运行态中run函数中的代码;

第四是阻塞态:线程正在运行的时候,被暂停,通常是为了等待某个事件的发生之后再继续运行,sleep,suspend,wait等方法导致线程阻塞;

第五是死亡态:如果一个线程的run方法执行结束或者调用stop方法后,该线程会死亡,对于已经死亡的线程,无法在使用start方法另其进入就绪态。

在Java中,线程通常有五种原因:

1. 调用sleep(毫秒数),使线程进入睡眠状态,在规定时间内,这个线程是不会运行的;

2. 调用suspend()暂停了线程的执行,除非线程收到resume()消息,否则不会运行;

3. 调用wait()暂停了线程的执行,除非线程收到notify()或notifyAll()消息,否则不会运行;

4. 线程等待一些IO操作的完成;

线程试图调用另一个对象的同步方法,但那个对象处于锁定状态,暂时无法使用。

0 0
原创粉丝点击