- /**
- * 第一种 同步代码快Synchronized(){}
- * */
- public class Thread0003 {
- public static void main(String[] args) {
- ThreadTest t = new ThreadTest();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- Thread t3 = new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- }
- }
- class ThreadTest implements Runnable {
- private static int tick = 100;
- Object obj = new Object();
- public void run() {
- while (true) {
- synchronized (obj) {
- if (tick > 0) {
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- }
- System.out.println(Thread.currentThread().getName() + ":"
- + tick--);
- }
- }
- }
- }
- }
复制代码 /**
* 第二种 同步函数
* */
public class Thread0004 {
public static void main(String[] args) {
ThreadTest1 t = new ThreadTest1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
class ThreadTest1 implements Runnable {
private static int tick = 100;
// Object obj = new Object();
public void run() {
while (true) {
// synchronized (obj) {
show();
// }
}
}
public synchronized void show() {
if (tick > 0) {
try {
Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName() + ":" + tick--);
}
}
} |