public class Chess implements Runnable{
public void run(){
move(Thread.currentThread().getId());
}
synchronized void move(long id){
System.out.println(id+" ");
System.out.println(id+" ");
}
public static void main(String[] args) {
Chess ch = new Chess();
new Thread(ch).start();
new Thread(new Chess()).start();
}
}
为什么是交替出来呢?非常不解。
public void run(){
move(Thread.currentThread().getId());
}
synchronized void move(long id){
System.out.println(id+" ");
System.out.println(id+" ");
}
public static void main(String[] args) {
Chess ch = new Chess();
new Thread(ch).start();
new Thread(new Chess()).start();
}
}
为什么是交替出来呢?非常不解。
■□■□■□■□■□■□■□■
□ □
■ 忍以明志 勤以致远 ■
□ □
■□■□■□■□■□■□■□■
基于CSDN论坛提供的插件扩展功能,自己做了个签名档工具,分享给大家,欢迎技术交流 :)
new Thread(ch).start();
new Thread(ch).start();
要么把同步做到类一级的
synchronized static void move(long id)
■□■□■□■□■□■□■□■
□ □
■ 忍以明志 勤以致远 ■
□ □
■□■□■□■□■□■□■□■
基于CSDN论坛提供的插件扩展功能,自己做了个签名档工具,分享给大家,欢迎技术交流 :)
public class ThreadLockDemo implements Runnable { public void run() {
while (true) {
synchronized (ThreadLockDemo.class) {
System.out.println("ticking " + Thread.currentThread().getId());
System.out.println("ticking " + Thread.currentThread().getId());
} try {
Thread.sleep(500L);
} catch (InterruptedException e) {
//
}
}
} public static void main(String[] args) {
new Thread(new ThreadLockDemo()).start();
new Thread(new ThreadLockDemo()).start();
}
}
方法加上 static synchronized 两个修饰,这样结果就是你的预期了。