Runnable类使用方法+与Thread区别

1、Runnable类使用

方法1

class Bank{
    private int sum;
    public void add(int n) {
        sum += n;
        System.out.println("sum = " + sum);
    }
}
class Cus1 implements Runnable{
    private Bank b = new Bank();
    public void run(){
        // 无锁状态会读脏数据
        for( int x = 0; x < 5; x++ ){
            b.add(1000);
        }
    }
}
class Cus2 implements Runnable{
    private Bank b = new Bank();
    public void run(){
        synchronized(b){ // 加锁
            for( int x = 0; x < 5; x++ ){
                b.add(100);
            }
        }
    }
}
public class Main{
    public static void main(String []args){
        //Cus1 c = new Cus1();
        Cus2 c = new Cus2();
        // 两个线程执行c对象
        Thread t1 = new Thread(c);
        Thread t2 = new Thread(c);
        t1.start(); t2.start();
    }
}

无锁状态下结果不稳定:


方法2

class Bank{
    private int sum;
    public synchronized void add(int n){
        sum += n;
        System.out.println("sum="+sum);
    }
}
class Cus implements Runnable{
    private Bank b=new Bank();
    public void run(){
        for(int x=0;x<5;x++) {
            b.add(100);
        }
    }
}
public class Main{
    public static void main(String []args){
        Cus c=new Cus();
        Thread t1=new Thread(c);
        Thread t2=new Thread(c);
        t1.start();
        t2.start();
    }
}

加锁状态下顺序正确:


2、Thread与Runnable区别

1、该段代码结果为三个线程各卖5张票,没有共享5张票

class MyThread extends Thread {
    private int ticket=5;
    public void run() {
        for(int i=0;i<20;i++) {
            if(this.ticket>0) {
                System.out.println("卖票:ticket"+this.ticket--);
            }
        }
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread mt1=new MyThread();
        MyThread mt2=new MyThread();
        MyThread mt3=new MyThread();
        mt1.start();
        mt2.start();
        mt3.start();
    }
}


2、三个线程共享5张票。

class MyThread implements Runnable {
    private int ticket=5;
    public void run() {
        for(int i=0;i<20;i++) {
            if(this.ticket>0) {
                System.out.println("卖票:ticket"+this.ticket--);
            }
        }
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值