java多线程示例:
package mythread;
public class ThreadTest {
public static void main(String[] args) {
Thread t1=new MyThreadA();
Thread t2=new MyThreadA();
Runnable mtb=new MyThreadB();
Thread t3=new Thread(mtb);
Thread t4=new Thread(mtb);
t1.setName("Thread-1");
t2.setName("Thread-2");
t3.setName("Thread-3");
t4.setName("Thread-4");
t1.start();
t2.start();
t3.start();
t4.start();
//Thread.currentThread();//main thread
System.out.println("main thread");
}
}
class MyThreadA extends Thread{
int i=0;
public void run() {
while(i<20){
i++;
for(int j=0;j<10000000;j++){
;
}
System.out.println(this.getName()+" i="+i);
}
}
}
class MyThreadB implements Runnable{
int i=0;
public void run() {
while(i<20){
synchronized(this){
if(i>=20){
break;
}
i++;
for(int j=0;j<10000000;j++){
;
}
System.out.println(Thread.currentThread().getName()+" i="+i);
}
}
}
}
如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。

