
java 多线程的例子
简单就是程序刚启动的时候去sql数据库中查找一个字段state,如果该字段有多条为1,有一个1就new出一个线程,这时候可能有多个线程,每个线程去执行一个操作,例如输出一句话,执行完后关闭改线程,这五个线程可以定义优先级,按顺序去执行 。希望new出的线程可以定义个数,不是有多少个1就有多少个线程,可灵活配置。
跪求大神啊
这五个线程 写错了 是这几个
===========
求详细代码 跪求大神 展开
多线程实际上就是多个线程同时运行,至于那个先完成是不能确定的。
* @author Rollen-Holt 实现Runnable接口
* */
class hello implements Runnable {
public hello() {
}
public hello(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 " + i);
}
}
public static void main(String[] args) {
hello h1=new hello("线程A");
Thread demo= new Thread(h1);
hello h2=new hello("线程B");
Thread demo1=new Thread(h2);
demo.start();
demo1.start();
}
private String name;
}
可能运行结果:
public class OutNumber {
private static int getThreadCountByDB()
{
/**
* jdbc code to get the No of 1...
* ...
*/
return 2;//假设返回2
}
public static void main(String[] args) {
int count = getThreadCountByDB();
for(int i = 0;i < count;i++){
Thread a = new Thread(new ThreadA());
a.start();
}
}
static class ThreadA implements Runnable{
@Override
public void run() {
System.out.println("我是刚new出来的线程!");
}
}
}
System.out.println(name+"运行,i="+i);
Thread.sleep(1)
}
for循环这样改就行了,因为输出10个数比较小,当你启动启动第二个线程时第一个线程已经运行完毕,所以两次输出都是顺序输出,要么将i设置很大很大,要么让每次打印暂停一下
广告 您可能关注的内容 |