public class thread {
public static void main (String[] args) {
Th1 t1 = new Th1(1);
new Thread(t1).start(); //方法1
Th1 t2 = new Th1(2);
t2.run();
t2.run();
t2.run(); //两种方法都可以
}
}
class Th1 implements Runnable {
private int thnum;
//记得要资源公共,要在run方法之前加上synchronized关键字,要不然会出现抢资源的情况
public synchronized void run () {
for (int i = 0; i < 50; i++) {
System.out.println("线程" + thnum + " 第" + i + "个数据" );
}
}
public Th1 (int thnum) {
this.thnum = thnum;
}
}
Java Runnable多线程理解(简单)
最新推荐文章于 2022-03-28 19:36:39 发布