多线程实际上就是多个线程同时运行,至于那个先完成是不能确定的。
* @author Rollen-Holt 实现Runnable接口
* */
class hello implements Runnable {
public hello() {
}
public hello(String name) {
this.name = name
}
public void run() {
for (int i = 0i <5i++) {
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
}
可能运行结果:
package epublic class A
{
public static void main(String args[]) throws Exception
{
new TestThread().start()
for(int i=0i<10i++)
{
Thread.sleep(3000)
System.out.println("main")
}
}
}
class TestThread extends Thread
{
public void run()
{
for(int i=0i<10i++)
{
System.out.println("Test")
}
}
}
for(int i=0i<10i++){System.out.println(name+"运行,i="+i)
Thread.sleep(1)
}
for循环这样改就行了,因为输出10个数比较小,当你启动启动第二个线程时第一个线程已经运行完毕,所以两次输出都是顺序输出,要么将i设置很大很大,要么让每次打印暂停一下