控制线程的第一种方法:线程的休眠
线程休眠的目的:防止cpu的占有率过高
public class Demo01 {
/**
* 线程的五种控制方法之一:线程的休眠
*/
public static void main(String[] args) {
for(int i=0;i<1000;i++)
{
System.out.println(Thread.currentThread().getName()+"----i="+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
一个例子:
public class Demo02 extends JFrame {
/**
* 让当前对象的时间显示出来
*/
//定义一个文本框
private JLabel show=new JLabel();
private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Demo02()
{
super("Demo02");
this.setResizable(false);
this.setSize(300,80);
this.setLocation(200,200);
show.setForeground(Color.RED);
show.setFont(new Font("微软雅黑",Font.BOLD,24));
//将给定的日期转换为字符串
show.setText(sf.format(new Date()));
new Thread(new Runnable() {
@Override
public void run() {
while(true)
{
show.setText(sf.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
this.add(show);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo02();
}
}
控制线程的第二种方法:守护线程
一个例子:
public class Demo03 {
/**
* 控制线程的第二种方法:守护线程setdaemon
* 如果被守护的线程执行完之后,守护线程执行一会儿就结束
*/
public static void main(String[] args) {
RunFor1 runFor1=new RunFor1();
//将runfor1设置为守护线程
runFor1.setDaemon(true);
runFor1.start();
for(int i=0;i<1000;i++)
{
System.out.println(Thread.currentThread().getName()+"----i="+i);
}
}
static class RunFor1 extends Thread{
RunFor1()
{
super("RunFor1");
}
@Override
public void run() {
for(int i=0;i<1000;i++)
{
System.out.println(Thread.currentThread().getName()+"----i="+i);
}
}
}
}
控制线程第三种方法的让步
一个例子:
public class Demo04 {
/**
* 线程控制的第三章方法:线程的让步yield
*/
public static void main(String[] args) {
MyT1 myT1=new MyT1("帅哥");
MyT1 myT2=new MyT1("美女");
myT1.start();
myT2.start();
}
static class MyT1 extends Thread{
private String name;
MyT1(String name)
{
super(name);
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "----i=" + i);
Thread.yield();
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}