public class Ticket extends Thread{
static int num = 0;
String name;
public Ticket(String name) {
this.name = name;
}
public synchronized void get(){
for(int i = 0;i<10;i++){
System.out.println(name+" "+num);
if(num==1000) return;
++num;
}
}
@Override
public void run() {
try {
System.out.println(name+"*********** "+num);
Thread.sleep(1000);
get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t100 = new Ticket("t100:");
Thread t200 = new Ticket("t200:");
Thread t3 = new Ticket("t3:");
t100.start();
t200.start();
List<Thread> list = new ArrayList<Thread>();
/*for(int i = 0;i<10;i++){
//new Thread("t"+i+":").start();
list.add(new Ticket("t"+i+":"));
}
for(int j = 0;j<list.size();j++){
//System.out.println(list.get(j));
list.get(j).start();
}*/
}
一次运行正常显示 多次就乱了
死锁,同步
TestSync.java
package Thread;
public class TestSync implements Runnable{
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 ......<br/><strong>答案就在这里:</strong><a target='_blank' rel='nofollow' href='http://blog.csdn.net/anskya520/article/details/6235493'>线程同步synchronized</a><br/>----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。
两个实例对象用的都不是同一把锁,肯定是不行的。
普通方法上使用synchronized,加锁对象是当前实例。
静态方法上使用synchronized,加锁对象是当前的类对象.class。
把方法改成静态方法,大家用的是同一个锁对象,就可以了。
package com.bin.test;
public class Ticket extends Thread {
static int num = 0;
public static synchronized void get() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + num);
if (num == 1000)
return;
++num;
}
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "*********** " + num);
Thread.sleep(1000);
get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t100 = new Ticket();
Thread t200 = new Ticket();
Thread t3 = new Ticket();
t100.start();
t200.start();
t3.start();
}
}