調用線程對象的run方法不會產生一個新的線程,雖然可以達到相同的執行結果,但執行過程和執行效率不同
package com.thread.wsleep.example1;
public class Hint {private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void product()
{
this.setCount(this.getCount() + 1);
}
public void consume()
{
this.setCount(this.getCount() - 1);
}
}
=====================================================
public class Thread1 implements Runnable {
private Hint hint;
public Thread1(Hint hint)
{
this.hint = hint;
}
@Override
public void run() {
try
{
synchronized(hint)
{
while(true)
{
while(this.hint.getCount()<10)
{
this.hint.product();
System.out.println("thread1 count:" + this.hint.getCount());
}
this.hint.notify();
this.hint.wait();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Hint getHint() {
return hint;
}
public void setHint(Hint hint) {
this.hint = hint;
}
}
=========================================================
package com.thread.wsleep.example1;
public class Thread2 implements Runnable {
private Hint hint;
public Thread2(Hint hint)
{
this.hint = hint;
}
@Override
public void run() {
try
{
synchronized(hint)
{
while(true)
{
while (this.hint.getCount() > 5)
{
this.hint.consume();
System.out.println("thread2 count: " + this.hint.getCount());
}
this.hint.notify();
this.hint.wait();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Hint getHint() {
return hint;
}
public void setHint(Hint hint) {
this.hint = hint;
}
}
=============================================================
package com.thread.wsleep.example1;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Hint hint = new Hint();
new Thread(new Thread1(hint)).start();
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
new Thread(new Thread2(hint)).start();
}
}