【Java基础_(线程篇_第一篇)】继承Thread;实现runnable;sleep、wait用法和区别;Thread和Runnable区别;线程停止

来源:互联网 发布:linux bg怎么用 编辑:程序博客网 时间:2024/05/20 11:51
一、线程两种实现

1.继承Thread类:

(1)【直接在主类继承】

package org;

// 继承 Thread 类
public class TestThreadofExt extends Thread
{
private static int count = 0;

public static void main(String[]args)
{
// new 一个 线程,然后启动
TestThreadofExt thread = new TestThreadofExt();
thread.start();
}

// 线程运行的内容
public void run()
{
count++;
System.out.println(count);
}
}

执行结果: 1
(我一开始以为,run中内容会一直执行,后来,理解了,线程执行完,就结束了)

(2)【内部类方式】

话外题:我晕,被内部类弄纠结了,好好学习一下:

内部类实例化: Outer.Inner outin = out.new Inner();

2.实现Runnable接口:




3.sleep和wait的区别:

(1)来自这篇博文<图有点误导人,但是点子说得还到位>:http://blog.csdn.net/darrenmu/article/details/21243035  


            大意如下:
              sleep(100):保持对象锁,仍然占有该锁;
               wait(100):释放对象锁。
(2)附sleep()的使用:

package org;// 继承 Thread 类public class TestThreadofExt extends Thread{    private static int count = 0;        public static void main(String[]args)    {        // new 一个 线程,然后启动        TestThreadofExt thread = new TestThreadofExt();        thread.start();    }        // 线程运行的内容    public void run()    {        try        {            threadContent();        }        catch (InterruptedException e)        {            e.printStackTrace();        }    }        private static void threadContent() throws InterruptedException    {        for(int i = 0;i < 10; i++)        {            count++;            System.out.println(count);            // 估计 slee()是Thread的静态方法,而"Thread"是来自JDK            Thread.sleep(2000);         }    }}


0 0
原创粉丝点击