java多線程02:線程通信
/*
* 子線程循環10次,接着主線程循環100,這個過程循環50次
*/
public class ThreadCommunication
{
public static void main(String[] args)
{
Business _business = new Business();
new Thread(new Runnable()
{
@Override
public void run()
{
for(int i = 0; i < 50; ++i)
{
//子線程循環10次
_business.subLoop(i + 1);
}
}
}).start();
for(int i = 0; i < 50; ++i)
{
//主線程循環100次
_business.mainLoop(i + 1);
}
}
}
/*
* 經驗:要用到共同數據(包括共享鎖)或共同算法的的若干個方法應該歸在同一個類身上,
* 這種設計正好體現了高類聚和程序的健壯性
* 鎖是上在代表要操作的資源的類的內部方法中,而不是線程代碼中
*/
class Business
{
//beShouldSub表示是否應該子線程執行
private boolean beShouldSub = true;
public synchronized void subLoop(int j)
{
//輪到主線程執行,子線程等待
while(!beShouldSub)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for(int i = 0; i < 10; ++i)
{
System.out.println("subLoop " + i + " Taltal loop " + j);
}
//子線程執行完,通知其他線程,這裏的其他線程只有主線程
beShouldSub = false;
this.notify();
}
public synchronized void mainLoop(int j)
{
while(beShouldSub)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for(int i = 0; i < 100; ++i)
{
System.out.println("mainLoop " + i + " Total loop " + j);
}
beShouldSub = true;
this.notify();
}
}
* 子線程循環10次,接着主線程循環100,這個過程循環50次
*/
public class ThreadCommunication
{
public static void main(String[] args)
{
Business _business = new Business();
new Thread(new Runnable()
{
@Override
public void run()
{
for(int i = 0; i < 50; ++i)
{
//子線程循環10次
_business.subLoop(i + 1);
}
}
}).start();
for(int i = 0; i < 50; ++i)
{
//主線程循環100次
_business.mainLoop(i + 1);
}
}
}
/*
* 經驗:要用到共同數據(包括共享鎖)或共同算法的的若干個方法應該歸在同一個類身上,
* 這種設計正好體現了高類聚和程序的健壯性
* 鎖是上在代表要操作的資源的類的內部方法中,而不是線程代碼中
*/
class Business
{
//beShouldSub表示是否應該子線程執行
private boolean beShouldSub = true;
public synchronized void subLoop(int j)
{
//輪到主線程執行,子線程等待
while(!beShouldSub)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for(int i = 0; i < 10; ++i)
{
System.out.println("subLoop " + i + " Taltal loop " + j);
}
//子線程執行完,通知其他線程,這裏的其他線程只有主線程
beShouldSub = false;
this.notify();
}
public synchronized void mainLoop(int j)
{
while(beShouldSub)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for(int i = 0; i < 100; ++i)
{
System.out.println("mainLoop " + i + " Total loop " + j);
}
beShouldSub = true;
this.notify();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.