------- android培训、java培训、期待与您交流! ----------
1、java中线程的实现 继承Thread
package com.test;
public class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
this.name = name;
}
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(name+"运行,i="+i);
}
}
}
主类为:
package com.test;
public class Main
{
public static void main(String[] args)
{
getMyThread();
}
public static void getMyThread()
{
MyThread mt1 = new MyThread("线程A");
MyThread mt2 = new MyThread("线程B");
mt1.start();
mt2.start();
}
}
2、实现Runnable接口
实现Runnable接口可以实现资源共享:
package com.test;
public class MyRunnable implements Runnable
{
private int ticket = 5;
public void run()
{
for(int i=0;i<100;i++)
{
if(ticket>0)
{
System.out.println("卖票:ticket="+ticket--);
}
}
}
}
public static void main(String[] args)
{
getRunnable();
}
public static void getRunnable()
{
MyRunnable my = new MyRunnable();
new Thread(my).start();
new Thread(my).start();
new Thread(my).start();
}
3、经典线程操作案例——生产者及消费者问题
生产的信息Info类:
package com.test;
public class Info
{
private String name = "李老师";
private String content = "Java老师";
private boolean flag = false;//设置标志
//加入同步
public synchronized void set(String name,String content)
{
if(!flag)
{
try
{
super.wait();//加入等待
} catch (Exception e)
{
// TODO: handle exception
}
}
this.setName(name);
try
{
Thread.sleep(3000);//线程休眠3秒
} catch (Exception e)
{
// TODO: handle exception
}
this.setContent(content);
flag = false;//修改标志位,表示可以取走
super.notify();//唤醒等待线程
}
//加入同步
public synchronized void get()
{
if(flag)
{
try
{
super.wait();//加入等待
} catch (Exception e)
{
// TODO: handle exception
}
}
try
{
Thread.sleep(3000);//线程休眠3秒
} catch (Exception e)
{
// TODO: handle exception
}
System.out.println(this.getName()+"--->"+this.getContent());
flag = true;//修改标志位为true,表示可以生产
super.notify();//唤醒等待线程
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
}
生产者类Producer:
package com.test;
public class Producer implements Runnable
{
private Info info = null;
public Producer(Info info)
{
this.info = info;
}
@Override
public void run()
{
// TODO Auto-generated method stub
boolean flag = false;
for(int i= 0 ;i<50;i++)
{
if(flag)
{
this.info.set("李老师", "Java讲师");
flag = false;
}else {
this.info.set("庐山", "美丽的风景区");
flag = true;
}
}
}
}
消费者类Customer:
package com.test;
public class Customer implements Runnable
{
private Info info = null;
public Customer(Info info)
{
this.info = info;
}
@Override
public void run()
{
// TODO Auto-generated method stub
for(int i = 0;i<50;i++)
{
try
{
Thread.sleep(100);
} catch (Exception e)
{
// TODO: handle exception
}
this.info.get();
}
}
}
主类:
public class Main
{
public static void main(String[] args)
{
Info info = new Info();
Producer producer = new Producer(info);
Customer customer = new Customer(info);
new Thread(producer).start();
new Thread(customer).start();
}
}