Toc
  1. 示例
Toc
0 results found
Espada
多线程之竞争与锁

示例

public class TestThread {

public static void main(String[] args) {
// new 出一个新的对象 t
ThreadFuck t1 = new ThreadFuck();
ThreadFuck t2 = new ThreadFuck();
// 两个线程
Thread thread1 = new Thread(t1, "Thread-1");
Thread thread2 = new Thread(t1, "Thread-2");
thread1.start();
thread2.start();
// t1.run();
}

}

class ThreadFuck implements Runnable {

int temp = 10;
// private Lock lock = new ReentrantLock();
@Override
public void run() {
// lock.lock();
for (int i = 0; i < 5; i++) {
temp -= 1;
try {
Thread.sleep(1);
} catch (InterruptedException ignored) {}
System.out.println(Thread.currentThread().getName() + "-temp = " + temp);
}
// lock.unlock();
}
}
龙鸣
"老罗"
本文作者:Espada
版权声明:本文首发于Espada的博客,转载请注明出处!