Android多线程研究(3)——线程同步和互斥及死锁

本文探讨Android开发中线程同步的概念,分析为何需要同步,并通过代码示例展示同步的重要性。同时,文章解释了死锁的概念,通过实例说明死锁情况,帮助理解线程间的协作问题。
摘要由CSDN通过智能技术生成

为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码:

package com.maso.test;

public class ThreadTest2 implements Runnable{
	private TestObj testObj = new TestObj();
	
	public static void main(String[] args) {
		ThreadTest2 tt = new ThreadTest2();
		Thread t1 = new Thread(tt, "thread_1");
		Thread t2 = new Thread(tt, "thread_2");
		t1.start();
		t2.start();
	}

	@Override
	public void run() {
		
		for(int j = 0; j < 10; j++){
			int i = fix(1);
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			System.out.println(Thread.currentThread().getName() + " :  i = " + i);
		}
		
	}
	
	public int fix(int y){
		return testObj.fix(y);
	}
	
	public class TestObj{
		int x = 10;
		
		public int fix(int y){
			return x = x - y;
		}
	}
	
	
}
输出结果后,就会发现变量x被两个线程同时操作,这样就很容易导致误操作。如何才能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值