62,616
社区成员
发帖
与我相关
我的任务
分享
class ThreadA {
/**
* @param args
*/
/**
* @param args
*/
public static void main(String[] args) {
Thread b = new Thread(new ThreadA());
//ThreadA b = new ThreadA();
b.start();
Object obj = new Object();
System.out.println("b is start....");
Thread c = new Thread();
c.start();
synchronized (c)// 括号里的b是什么意思,起什么作用?
{
try {
//Thread.sleep(20);
//b.setTotal();
System.out.println("Waiting for b to complete...");
c.wait();// 这一句是什么意思,究竟让谁wait?
System.out.println("Completed.Now back to main thread");
} catch (InterruptedException e) {
}
}
}
}
public class ThreadA implements Runnable {
public int total;
public void setTotal(){
total++;
}
public void run(){
synchronized (this) {
System.out.println("ThreadA is running..");
/*try{
Thread.sleep(1000);
}catch(InterruptedException e){}*/
for (int i = 0; i < 20; i++) {
total += i;
System.out.println("total is " + total);
}
notify();
}
}
}
package cn.leisore.daily._2010_06_03;
public class ThreadMain {
public static void main(String[] args) {
final Thread t = new Thread(){
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
new Thread(){
public void run() {
synchronized (t)
{
try {
t.wait();
System.out.println("t1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run() {
synchronized (t)
{
try {
t.wait();
System.out.println("t2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
public class ThreadA {
/**
* @param args
*/
/**
* @param args
*/
public static void main(String[] args) {
Thread b = new Thread(new ThreadC());// 注意这里有两个对象,一个是Thread类型的b,一个是ThreadC类型的匿名对象。
// ThreadC b = new ThreadC();
b.start();
System.out.println("b is start....");
synchronized (b)// 这里是一个b的同步块(不明白就百度一下)
{
try {
// Thread.sleep(20);
// b.setTotal();
System.out.println("Waiting for b to complete...");
b.wait();// 让获得b对象锁的当前线程wait,在这里即本线程。
System.out.println("Completed.Now back to main thread");
} catch (InterruptedException e) {
}
}
}
}
class ThreadC implements Runnable {
public int total;
public void setTotal() {
total++;
}
public void run() {
synchronized (this) {// 这个同步块加到上面提到的匿名对象上了,并没有加到外围的b上面。这就是为什么LZ觉得两个线程同时获得了同一个对象的锁(其实是不同的两个对象,所以两个线程能够同时进入)。
System.out.println("ThreadC is running..");
/*
* try{ Thread.sleep(1000); }catch(InterruptedException e){}
*/
for (int i = 0; i < 20; i++) {
total += i;
System.out.println("total is " + total);
}
notify();
}
}
}