我这里有一个java thread的例程,
你可以看着改一下啊。
//: Cartoon.java
// Constructor calls during inheritance
package wkai;
import java.util.*;
import java.lang.Object;
class Summation extends Thread
{
public Summation(int n){
upper = n ;
}
public void run(){
int sum=0;
if(upper>0){
for(int i=1;i<=upper;i++)
sum+=i;
}
System.out.println("The sum of"+upper+"is "+sum );
}
private int upper;
}
class wkai
{
public static void main(String[] args)
{
if(args.length>0){
if(Integer.parseInt(args[0]<0))
System.err.println(args[0]+"must be>=0");
else
{
Summation thrd =new Summation(Integer.parseInt(args[0]));
thrd.start();
}
}
else
System.err.println("……"); }
}
你可以看着改一下啊。
//: Cartoon.java
// Constructor calls during inheritance
package wkai;
import java.util.*;
import java.lang.Object;
class Summation extends Thread
{
public Summation(int n){
upper = n ;
}
public void run(){
int sum=0;
if(upper>0){
for(int i=1;i<=upper;i++)
sum+=i;
}
System.out.println("The sum of"+upper+"is "+sum );
}
private int upper;
}
class wkai
{
public static void main(String[] args)
{
if(args.length>0){
if(Integer.parseInt(args[0]<0))
System.err.println(args[0]+"must be>=0");
else
{
Summation thrd =new Summation(Integer.parseInt(args[0]));
thrd.start();
}
}
else
System.err.println("……"); }
}
解决方案 »
- public static void main(String\u005B\u005D args)这是什么
- 字符串变成double型
- 求帮忙,偶新手来的
- 为什么不能交换参数的值
- 再次讨论int、byte编译问题
- 请问一下,数据库连接池的问题~~~~
- 在网上找了个全英文的java源代码(里边的字符是英文的),为什么我在记事本里修改字符后,编译后不能显示???
- 刚毕业的在上海java程序员的薪资水平怎么样???
- 初学者 的 问题
- 集思广益----想做一个由购物车功能的网站,有什么做最方便?
- 急问:关于socket的问题!!
- 请教:当我点击菜单使菜单下拉时,这时候我又点击最小化按钮让窗体最小化,然后最大化,这时候我的菜单就会留下一个影子,去不掉,这是什
里面的核心是
Summation thrd =new Summation(Integer.parseInt(args[0]));
thrd.start();
其他的都可以删除。
public class ThreadTester {
public static StringBuffer isReady = new StringBuffer("no"); private static void wait0(int second) {
try{
Thread.sleep(second*1000);
}catch(InterruptedException e){}
}
public static void main(String[] args) {
// producer thread
new Thread(new Runnable() {
public void run() {
while(true) {
synchronized(isReady) {
if(isReady.toString().equals("no") ) {
System.out.println("get data from DB");
isReady.delete(0,isReady.length());
isReady.append("yes");
isReady.notify();
}
try {
isReady.wait();
}catch(InterruptedException e){}
wait0(3);
}
}
}
}).start();// consumer thread
new Thread(new Runnable() {
public void run() {
while(true) {
synchronized(isReady) {
if(isReady.toString().equals("yes") ) {
System.out.println(" processing data");
isReady.delete(0,isReady.length());
isReady.append("no");
isReady.notify();
}
try {
isReady.wait();
}catch(InterruptedException e){}
}
}
}
}).start();
}
}
Summation thrd =new Summation(Integer.parseInt(args[0]));
thrd.start();
那不就是唤醒B吗?
class Summation extends Thread里面做好了,返回,
不就相当于唤醒了A?
1、设置一个全局变量,用于标识产品是否已经被消费:isConsumed
2、在生产者线程中,当然要注意线程同步的问题了
while (! isConsumed)
wait();
生产产品;
notify();
3、在消费者线程中
while (isConsumed)
wait();
消费产品;
notify();
代码也是这个道理,其实可以扩展到好几个线程之间也可使用此方式进行通信。