多线程

作者: 非非非非常胖的大公鸡9527 | 来源:发表于2018-07-23 20:30 被阅读0次

一、编写多线程分为两种:

1.继承Thread类

2.实现runnable接口


package com.company;

class Mythreadextends Thread{

private Stringname;

public Mythread(String name){

this.name = name;

}

public void run(){

for (int i=0;i<=10;i++){

System.out.println(String.format("线程名:%s\n值为:%s",name,i));

}}}

class Myrunnableimplements Runnable{

private int num=5;

public void run(){

for(int i=0;i<5;i++) {

synchronized (this) {

if (num >0) {

try {

Thread.sleep(1000);

}catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("the number is :" +num--);

}}}}}

public class ThreadTest {

public static void main(String[] args){

//        Mythread t1 = new Mythread("线程1");

//        Mythread t2 = new Mythread("线程2");

//        t1.start();

//        t2.start();

        Myrunnable t3 =new Myrunnable();

new Thread(t3).start();

new Thread(t3).start();

}}

二、Runable相对于Thread的好处:
1.Runable适合多个相同代码程序去处理同一资源
2.Thread只能单继承,比较局限
3.增强代码的健壮性,代码可以被多个线程共享,代码和数据是独立的

三、线程休眠

Thread.sleep(1000)     //休眠一秒

四、同步和死锁
如果多个线程是实现的Runnable接口,则这个类的属性将被多个线程共享,所以容易出现同步的问题;
解决:1.在run里面加入synchonized(this),这是同步了代码块
2.将run里面的逻辑操作代码分离出来,写成一个方法,在方法面前加synchonized,然后在run里面调用这个方法

死锁:两个线程都掌握着资源,并且都在等待对方释放自己的资源,造成了代码的停滞。

相关文章

  • iOS多线程 NSOperation

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程 pthread、NSThread

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程: GCD

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程运用

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程基础

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • 多线程介绍

    一、进程与线程 进程介绍 线程介绍 线程的串行 二、多线程 多线程介绍 多线程原理 多线程的优缺点 多线程优点: ...

  • iOS进阶之多线程管理(GCD、RunLoop、pthread、

    深入理解RunLoopiOS多线程--彻底学会多线程之『GCD』iOS多线程--彻底学会多线程之『pthread、...

  • iOS多线程相关面试题

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • 多线程之--NSOperation

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • iOS多线程之--NSThread

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

网友评论

      本文标题:多线程

      本文链接:https://www.haomeiwen.com/subject/gjfsmftx.html