曰本做爰视频网站,新网站建设需要什么,wordpress 开店,云主机 怎么做网站1.在使用线程时#xff0c;为什么不直接调用run()方法而是调用了start(): 直接调用run()方法#xff0c;不存在线程的启动#xff0c;属于调用实例方法#xff0c;只有一条执行路径#xff0c;不存在多线程并行交替执行了。调用start()方法属于启动线程#xff0c;将自动… 1.在使用线程时为什么不直接调用run()方法而是调用了start(): 直接调用run()方法不存在线程的启动属于调用实例方法只有一条执行路径不存在多线程并行交替执行了。调用start()方法属于启动线程将自动调用run()方法 2.子线程循环 10次接着主线程循环 100次接着又回到子线程循环 10次接着再回到主线程又循环 100次如此循环50次 public class ThreadTest{ public static void main(String[] args) { final MyThread threadsnew MyThread(); new Thread( new Runnable(){ public void run(){ for(int i1;i50;i){ threads.subThread(i); } } } ).start(); new Thread(new Runnable(){ public void run(){ for(int i1;i50;i){ threads.mainThread(i); } } }).start(); }
} class MyThread{ boolean bShouldSubtrue;//标志子线程方法是否被调用 public synchronized void subThread(int i){ if(!bShouldSub){//若子线程没被调用即主线程正在运行所以等待 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j1;j10;j){ System.out.println(sub thread :i,loop : j); } bShouldSubfalse;//子线程运行完毕 this.notify();//唤醒其他线程即主线程 } public synchronized void mainThread(int i){ if(bShouldSub){//若子线程正在被调用所以等待 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j1;j100;j){ System.out.println(main thread :i,loop : j); } bShouldSubtrue;//主线程调用完毕 this.notify();//唤醒子线程 }
} 3.编写一个程序开启3个线程这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍要求输出结果必须按ABC的顺序显示 public class TestThread { /** * author lucky */ public static void main(String[] args) { new Thread(new TestRun(A)).start(); new Thread(new TestRun(B)).start(); new Thread(new TestRun(C)).start(); } } class TestRun implements Runnable { private String name; private static String flag A; private int count 10; TestRun(String name) { this.name name; } Override public void run() { while (count 0) { synchronized (flag) { if (flag.equals(name)) { System.out.print(name); count--; if (name.equals(A)) flag B; if (name.equals(B)) flag C; if (name.equals(C)) flag A; } } } } } 4.wait()方法和sleep()方法的区别 1.wait()方法用于将当前线程处于等待状态它是Object类的sleep()是将当前线程休眠它是Thread 2.wait()将锁释放sleep()方法不会释放锁 5.生产者和消费者 转载于:https://www.cnblogs.com/xiao-ran/p/10735496.html