黑马程序员_多线程

------- android培训java培训、期待与您交流! ---------- 

java中的多线程

           在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

class 类名 extends Thread{
方法1;
方法2
public void run(){
// other code…
}
属性1
属性2
  
}

这种方式有个局限性:这样设计的话该类就无法再去继承其他的类了。。。所以我们主要还是用的另一种方式。

class 类名 implements Runnable{
方法1;
方法2
public void run(){
// other code…
}
属性1
属性2
  
}

这样我们就可以既继承其他类有实现多线程了。特别注意的是,一定要记得实现run方法哦。

来看个小例子吧

class hello implements Runnable {
  
    public hello() {
  
    }
  
    public hello(String name) {
        this.name = name;
    }
  
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
    }
  
    public static void main(String[] args) {
        hello h1=new hello("线程A");
        Thread demo= new Thread(h1);
        hello h2=new hello("线程B");
        Thread demo1=new Thread(h2);
        demo.start();
        demo1.start();
    }
  
    private String name;
}

当有多个线程同时操作run方法里面涉及到相同的数据时,我们需要加上一个synchronized关键字来保证线程的同步。否则就有可能出现数据的错乱。

 public void run() {

                   synchronized(hello.class)

                 {

        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
       }
    }

这样就可以避免一些问题的出现了

synchronized块我们称之为同步代码块。当一个线程对象进去时,另一个线程对象就无法进去了,只能在外面等着,一直等到那个线程执行完了出来了,它才有机会进去。

如果我们没有指定名字的话,系统自动提供名字。

提醒一下大家:main方法其实也是一个线程。在java中所以的线程都是同时启动的,至于什么时候,哪个先执行,完全看谁先得到CPU的资源。

线程的休眠:

class hello implements Runnable {
    public void run() {
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
  
    public static void main(String[] args) {
        hello he = new hello();
        Thread demo = new Thread(he, "线程");
        demo.start();
    }
}

线程的中断:

class hello implements Runnable {
    public void run() {
        System.out.println("执行run方法");
        try {
            Thread.sleep(10000);
            System.out.println("线程完成休眠");
        } catch (Exception e) {
            System.out.println("休眠被打断");
            return//返回到程序的调用处
        }
        System.out.println("线程正常终止");
    }
  
    public static void main(String[] args) {
        hello he = new hello();
        Thread demo = new Thread(he, "线程");
        demo.start();
        try{
            Thread.sleep(2000);
        }catch (Exception e) {
            e.printStackTrace();
        }
        demo.interrupt(); //2s后中断线程
    }
}

线程虽然有点复杂,但是还是得一点一点的啃呀。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值