线程概念:

1、线程是轻量级的进程

2、线程没有独立的地址空间(内存空间)

3、线程由进程创建(寄生于进程)

4、一个进程可以拥有多个线程(多线程编程)

5、线程有几种状态:

a、新建状态

b、就绪状态

c、运行状态

d、阻塞状态

e、死亡状态

Java学习:线程基础(一)

线程如何使用

在java中一个类要当做线程使用有两种方法:

1、继承Thread类,并重写run函数

案例1:编写一个程序,该程序可以每隔一秒在控制台输出“hello,world”。

public class ThreadTest { public static void main(String[] args) {// 创建一个Cat对象 Cat cat = new Cat(); // 启动线程,会导致run函数的运行 cat.start(); } } class Cat extends Thread { // 重写run函数 public void run() { while (true) { // 休眠一秒(1000毫秒)线程进入阻塞状态 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("hello,world"); } } }

执行结果:

Java学习:线程基础(一)

案例2:编写一个程序,该程序可以每隔一秒在控制台输出“hello,world”,当输出10次后,自动退出。

public class ThreadTest { public static void main(String[] args) {// 创建一个Cat对象 Cat cat = new Cat(); // 启动线程,会导致run函数的运行 cat.start(); } } class Cat extends Thread { // 重写run函数 int times = 0; public void run() { while (true) { // 休眠一秒(1000毫秒)线程进入阻塞状态 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } times++; System.out.println("hello,world" + times); if (times == 10) { break; } } } }

执行结果:

Java学习:线程基础(一)

2、实现Runnable接口,并重写run函数(解决Java不能多重继承的问题)

public class RunnableTest { public static void main(String[] args) { Cat cat = new Cat(); // 注意启动方法 Thread t = new Thread(cat); t.start(); } } class Cat implements Runnable { // 重写run函数 int times = 0; public void run() { while (true) { // 休眠一秒(1000毫秒)线程进入阻塞状态 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } times++; System.out.println("hello,world" + times); if (times == 10) { break; } } } }

注意实现Runnable接口创建多线程时线程的启动方式。

执行结果:

Java学习:线程基础(一)

相关文章: