java 韩顺平 第38_韩顺平java笔记 第38讲 第39讲 第40讲 线程

1.线程

(1)线程是轻量级的进程

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

线程是由进程创建的(寄生在进程)

一个进程可以有多个线程

(2)线程有几种状态

a 新建状态(new)

b就绪状态(Rannable)

c运行状态(Running)

d阻塞状态(Blocked)

e死亡状态(Dead)

(3)在java中一个类要当作线程来使用有两种方法

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

2、实现runnable接口,并重写run函数

(某些情况下,一个类已经继承了某个父类就不能继承thread类了)

2.通过继承Thread类来实现建立线程实例

public classThread{

public static void main(String[] args){

Cat cat = new Cat();

cat.start();

}

}

class Cat extends Thread{

int times = 0;

public void run(){//重写run函数

while(true){

try{//休眠1秒

Thread.sleep(1000);

}catch(Exception e){

e.printStackTrace();

}

times++;

System.out.println("hello,word!" + times);

if(times == 10){

break;//退出线程

}

}

}

}

3.通过Runnable 接口来实现建立线程实例

public class Thread{

public static void main(String []args){

Dog dog = new Dog();

Thread t = new Thread(dog);//创建线程

t.start();//启动线程

}

}

class Dog implements Runnable{

public void run(){//重写run函数

int times = 0;

while(true){

try{

Thread.sleep(1000);

}catch(Exception e){

e.printStackTrace();

}

times ++;

System.out.println("hello" + times);

if(times == 10){

break;

}

}

}

}

4.一个线程通过接收n来执行1+...+n得到和,

另一个线程每隔1秒输出一次hello world

public class Thread{

public static void mian(String[] args){

Pig pig = new Pig(10);

Bird bird = new Bird(10);

Thread t1 = new Thread(pig);//建立线程

Thread t2 = new Thread(bird);

t1.start();//启动线程

t2.start();

}

}

class Pig implements Runnable{//打印hello world

int n=0;

int times = 0;

public Pig(int n){

this.n=n;

}

public void run(){

while(true){

try{

Thread.sleep(1000);

}catch(Exception e){

e.printStacktrace();

}

times++;

System.out.println("打印hello  word");

if(times ==n){

break;

}

}

}

}

class Bird implements Runnable{//

int n=0;

int res=0;

int times = 0;

public Bird(int n){

this.n = n;

}

public void run(){

while(true){

try{

Thread.sleep(1000);

}catch(Exception e){

e.printStackTrace();

}

res +=(++times);

System.out.println("结果是:"+res);

if(times==n){

System.out.println("最后结果是:"+res);

break;

}

}

}

}

42529dd076d0987a94371188896a9261.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值