java多线程代码 java多线程代码例子

java线程的经典代码package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多线程测试java多线程代码!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
【java多线程代码 java多线程代码例子】 }
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好吗java多线程代码?");
System.out.println("正在进行的Thread是java多线程代码:" + t);
try {
for (int i = 0; i5; i++) {
System.out.println("java多线程代码我不叫穆继超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一个主进程");
System.out.println("正在运行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在创建一个进程");
t2.start();
try {
System.out.println("使他进入第一个睡眠状态");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第一个进程");
}
public void run() {
try {
for (int i = 0; i5; i++) {
System.out.println("进程" + i);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第二个进程");
}
public static void main(String[] args) {
new threadDemo2();
}
}
java 如何实现多线程java中多线程的实现方式有两种,一种是继承java.lang.Thread类,另一种是实现java.lang.Runnable接口 。下面是两种方式的简单代码 。继承Thread类方式:import java.lang.Thread; //用集成Thread类方式实现多线程 。public class Test{ public static void main(String arg[]){ T t1=new T(); T t2=new T(); //更改新线程名称 t1.setName("t1"); t2.setName("t2"); //启动线程 t1.start(); t2.start(); } } class T extends Thread{ //重写run()方法 public void run(){ System.out.println(this.getName()); } }输出结果为:t1t2实现Runnable接口方式:在使用Runnable接口时需要建立一个Thread实例 。因此,无论是通过Thread类还是Runnable接口建立线程 , 都必须建立Thread类或它的子类的实例 。import java.lang.*; //用实现Runnable接口的方式实现多线程 。public class Test{ public static void main(String arg[]){ T t1=new T(); T t2=new T(); //一定要实例化Thread对象 , 将实现Runnable接口的对象作为参数传入 。Thread th1=new Thread(t1,"t1"); Thread th2=new Thread(t2,"t2"); //启动线程 th1.start(); th2.start(); } } class T implements Runnable{ //重写run()方法 public void run(){ System.out.println(Thread.currentThread().getName()); } }输出结果为:t1t2public void run()方法是JAVA中线程的执行体方法,所有线程的操作都是从run方法开始,有点类似于main()方法,即主线程 。

推荐阅读