您的位置:首页 > 移动开发 > Android开发

android开发 线程同步锁

2016-03-17 17:46 429 查看
package test;

public class MyThread implements Runnable{

public void run() {

for(int i = 5000 ; i > 0 ; i--){
synchronized (this) {
System.out.println(Thread.currentThread().getName() + i);

Thread.yield();
}
}

}
}

package test;

public class Test {
public static void main(String args []) {

MyThread myThread = new MyThread();

Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);

thread1.setName("线程1 ");
thread2.setName("线程2 ");

thread1.start();
thread2.start();

}
}

补充:还用同步方法 和上面用法相似 只是把synchronized关键字写在了方法名前面 比如:

public synchronized void run(){

  //code

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: