线程的让步

线程让出自己占用的CPU资源

  • 线程让出资源,不指定让给谁
  • 线程让出资源,指定让给谁

方法1:

public static void yield();

线程实现交替打印

import java.io.*;
import java.util.*;
class MyRunnable implements Runnable{
private String l;
private String r;
public MyRunnable(String fl,String fr) {
this.l=fl;this.r=fr;
}
public void run() {
for(int i=0;i<30;i++) {
System.out.print(l+" "+i+" "+r+" ");
Thread.yield();
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable mr1=new MyRunnable("[","]");
MyRunnable mr2=new MyRunnable("(",")");
Thread t1=new Thread(mr1);
Thread t2=new Thread(mr2);
t1.start();t2.start();
}
}

方法2:

public final void join() throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join(long millis,int nano) throws InterruptedException

将两个线程合并为同一个线程,A调用join B,A等到B结束再恢复执行

import java.io.*;
import java.util.*;
class MyRunnable implements Runnable{
private String l;
private String r;
public MyRunnable(String fl,String fr) {
this.l=fl;this.r=fr;
}
public void run() {
for(int i=0;i<30;i++) {
System.out.print(l+" "+i+" "+r+" ");
Thread.yield();
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable mr1=new MyRunnable("[","]");
Thread t1=new Thread(mr1);
t1.start();
for(int i=0;i<30;i++) {
if(i==10) {
try {
System.out.print("Join");
t1.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("( "+i+" )");
}
}
}

方法3:

public final void setDaemon(boolean on) //将某个线程设置为守护线程

方法4:

public static void sleep(long millis)throws InterruptedExcepiton

线程同步


方法1:

synchronized 加锁
class Resources{
synchronized void function1(Thread currThread) {
for(int i=0;i<300;i++) {
System.out.println(currThread.getName());
}
}
}
class MyThread extends Thread{
Resources rs;
public MyThread(String tname,Resources trs) {
this.setName(tname);
this.rs=trs;
}
public void run() {
if(this.getName().equals("Thread1")) {
System.out.println("Thread1启动,等待进入function1");
rs.function1(this);
}else {
System.out.println("Thread2启动,等待进入function1");
rs.function1(this);
}
}
}
public class Main {
public static void main(String[] args) {
Resources rs=new Resources();
MyThread t1=new MyThread("Thread1",rs);
MyThread t2=new MyThread("Thread2",rs);
t1.start();t2.start();
}

方法2:

public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void notify()
public final void notifyAll()
05-18 07:39
查看更多